forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseLinkedList.java
58 lines (53 loc) · 1.2 KB
/
ReverseLinkedList.java
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
// Source : https://leetcode.com/problems/reverse-linked-list/description/
// Author : Tianming Cao
// Date : 2018-02-11
/**********************************************************************************
*
* Reverse a singly linked list.
*
* Hint:
* A linked list can be reversed either iteratively or recursively. Could you implement both?
*
**********************************************************************************/
package reverseLinkedList;
public class ReverseLinkedList {
/**
* The iterative solution
*/
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
ListNode p = head;
ListNode next = p.next;
while (next != null) {
ListNode temp = next.next;
next.next = p;
p = next;
next = temp;
}
head.next = null;
return p;
}
public ListNode reverseListRecursion(ListNode head) {
if (head == null) {
return head;
}
ListNode newHead = recursion(head);
head.next = null;
return newHead;
}
/**
* The recursive solution
*/
public ListNode recursion(ListNode p) {
if (p.next == null) {
return p;
} else {
ListNode next = p.next;
ListNode newHead = recursion(next);
next.next = p;
return newHead;
}
}
}