[LintCode] Reverse Linked List 倒置链表
Reverse a linked list.
Example
For linked list 1->2->3
, the reversed linked list is 3->2->1
Challenge
Reverse it in-place and in one-pass
LeetCode上的原题,请参见我之前的博客Reverse Linked List。
解法一:
class Solution { public: /** * @param head: The first node of linked list. * @return: The new head of reversed linked list. */ ListNode *reverse(ListNode *head) { if (!head) return NULL; ListNode *dummy = new ListNode(-1), *cur = head; dummy->next = head; while (cur->next) { ListNode *t = cur->next; cur->next = t->next; t->next = dummy->next; dummy->next = t; } return dummy->next; } };
解法二:
class Solution { public: /** * @param head: The first node of linked list. * @return: The new head of reversed linked list. */ ListNode *reverse(ListNode *head) { if (!head || !head->next) return head; ListNode *t = head; head = reverse(t->next); t->next->next = t; t->next = NULL; return head; } };