-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
reverseLinkedList.cpp
50 lines (46 loc) · 1.29 KB
/
reverseLinkedList.cpp
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
// Source : https://leetcode.com/problems/reverse-linked-list/
// Author : Hao Chen
// Date : 2015-06-09
/**********************************************************************************
*
* Reverse a singly linked list.
*
* click to show more hints.
*
* Hint:
* A linked list can be reversed either iteratively or recursively. Could you implement both?
*
*
**********************************************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList_iteratively(ListNode* head) {
ListNode *h=NULL, *p=NULL;
while (head){
p = head->next;
head->next = h;
h = head;
head = p;
}
return h;
}
ListNode* reverseList_recursively(ListNode* head) {
if (head==NULL || head->next==NULL) return head;
ListNode *h = reverseList_recursively(head->next);
head->next->next = head;
head->next = NULL;
return h;
}
ListNode* reverseList(ListNode* head) {
return reverseList_iteratively(head);
return reverseList_recursively(head);
}
};