题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
解题思路1:
迭代法
代码1:
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head):
pre, cur = None, head
while cur:
nextTemp = cur.next
cur.next = pre
pre, cur = cur, nextTemp
return pre
c++写法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return NULL;
auto a = head, b = head -> next;
while(b){
auto c = b -> next;
b -> next = a;
a = b, b = c;
}
head -> next = NULL;
return a;
}
};
解题思路2:
递归法
代码2:
class Solution:
def reverseList(self, head):
if not head or not head.next:
return head
nextNode = self.reverseList(head.next)
head.next.next = head
head.next = None
return nextNode
参考链接:
题目来源: