206. Reverse Linked List
Reverse a linked list
Thoughts:
Using Stack (time limit exceed)
Recursively: Find the second from the last node (if it Linked List contains more than two nodes), then reverse current two nodes by first creating a cycle, then cut the forward links (set it to be NULL/nullptr)
Having three pointers
first record next node and then set current node next to pre
repeat for the next step: move pre to head and then move head to next
having three pointers with dummy node:
pre always inserts cur->next right next to itself
Code 2
/**
* 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 || !head->next) return head;
ListNode* node = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return node;
}
};Code 3
Code 4
Special Thanks to jianchaolifighter's Solution and and redace85's Solution
Last updated
Was this helpful?