# 206. Reverse Linked List 反转链表

@TOC

[LeetCode]

Total Accepted: 105474 Total Submissions: 267077 Difficulty: Easy

## # 题目描述

Example:

``````Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
``````

A linked list can be reversed either iteratively or recursively. Could you implement both?

## # 解题方法

### # 迭代

``````old->3->4->5->NULL
new->2->1

old->4->5->NULL
new->3->2->1
``````

Java代码如下：

``````public ListNode reverseList(ListNode head) {
ListNode prev = null;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
``````

``````# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""
``````

``````# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""
dummy = ListNode(-1)
return dummy.next
``````

``````/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* dummy = new ListNode(0);
ListNode* old = dummy->next;
}
return dummy->next;
}
};
``````

### # 递归

1 → … → nk-1 → nk → nk+1 → … → nm → Ø

Assume from node nk+1 to nm had been reversed and you are at node nk.

n1 → … → nk-1 → nk → nk+1 ← … ← nm

We want nk+1’s next node to point to nk.

So,

nk.next.next = nk;

Be very careful that n1's next must point to Ø. If you forget about this, your linked list has a cycle in it. This bug could be caught if you test your code with a linked list of size 2.

Java代码如下：

``````public ListNode reverseList(ListNode head) {
return p;
}
``````

python的递归写法。

``````# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""

``````

C++代码如下：

``````/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public: