-
Notifications
You must be signed in to change notification settings - Fork 92
/
ReverseLinkedList206.java
94 lines (76 loc) · 2.12 KB
/
ReverseLinkedList206.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* Reverse a singly linked list.
*
* Hint:
* A linked list can be reversed either iteratively or recursively.
* Could you implement both?
*
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class ReverseLinkedList206 {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
ListNode tail = null;
while (head != null) {
ListNode t = head;
head = head.next;
tail = dummy.next;
dummy.next = t;
dummy.next.next = tail;
}
return dummy.next;
}
public ListNode reverseList2(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
helper(head, dummy);
return dummy.next;
}
private void helper(ListNode head, ListNode dummy) {
if (head == null) return;
ListNode curr = head;
head = head.next;
ListNode tail = dummy.next;
dummy.next = curr;
dummy.next.next = tail;
helper(head, dummy);
}
public ListNode reverseList3(ListNode head) {
return helper2(head, null);
}
private ListNode helper2(ListNode head, ListNode h) {
if (head == null) return h;
ListNode tail = head.next;
head.next = h;
return helper2(tail, head);
}
/**
* https://leetcode.com/problems/reverse-linked-list/solution/
*/
public ListNode reverseList4(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
public ListNode reverseList5(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}