-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path206.ReverseLinkedList.h
More file actions
61 lines (43 loc) · 1.16 KB
/
206.ReverseLinkedList.h
File metadata and controls
61 lines (43 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
2015-07-08
bluepp
May the force be with me!
Reverse a singly linked list.
https://leetcode.com/problems/reverse-linked-list/
*/
/* iteration */
ListNode* reverseList(ListNode* head) {
ListNode *pCurr = head, *prev = NULL;
while (pCurr)
{
ListNode *pNext = pCurr->next;
pCurr->next = prev;
prev = pCurr;
pCurr = pNext;
}
return prev;
}
/* 2018/10/26 */
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
ListNode *p = head;
head = reverseList(p->next);
p->next->next = p;
p->next = NULL;
return head;
}
/* recursion */
ListNode* reverseList(ListNode* head) {
reverse(head);
return head;
}
void reverse(ListNode *&head)
{
if (!head) return;
ListNode *rest = head->next;
if (!rest) return;
reverse(rest);
head->next->next = head;
head->next = NULL;
head = rest;
}