Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
思路:把当前链表的下一个节点cur插入到头结点dummy的下一个节点中,就地反转。
dummy->1->2->3->4->5的就地反转过程:
dummy->2->1->3->4->5
dummy->3->2->1->4->5
dummy->4>-3->2->1->5
dummy->5->4->3->2->1
cur是需要反转的节点。
1 pre连接下一次需要反转的节点
2 反转节点cur
3 纠正头结点dummy的指向
4 cur指向下一次要反转的节点
解法一:
/**
* 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(0);
dummy.next = head;
ListNode *pre = head;
ListNode *cur = pre->next;
while(cur){
pre->next = cur->next;
cur->next = dummy.next;
dummy.next = cur;
cur = pre->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) {
ListNode dummy(0);
ListNode *cur = head;
while(cur){
ListNode *nex = cur->next;
cur->next = dummy.next;
dummy.next = cur;
cur = nex;
}
return dummy.next;
}
};
解法三:递归到最后一个结点当为newHead,向前逐步反向连接。
/**
* 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 *newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
};