Reverse a singly linked list.
解题思路:
利用头节点,头插法。
/**
* 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 == NULL) return NULL;
ListNode dummy(-1);
dummy.next = head;
ListNode *prev = &dummy;
ListNode *cur = head;
ListNode *next = head->next;
while (cur != NULL && next != NULL) {
cur->next = next->next;
next->next = prev->next;
prev->next = next;
next = cur->next;
}
return dummy.next;
}
};
递归版本:
/**
* 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 == NULL || head->next == NULL) return head;
ListNode *p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};