-
Notifications
You must be signed in to change notification settings - Fork 2
/
ReverseLinkedList.java
38 lines (37 loc) · 943 Bytes
/
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class IterativeSolution {
public ListNode reverseList(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = head;
while (p != null && p.next != null) {
ListNode temp = p.next;
p.next = temp.next;
temp.next = dummy.next;
dummy.next = temp;
}
return dummy.next;
}
}
public class RecursiveSolution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode next = head.next;
head.next = null;
ListNode reverseRest = reverseList(next);
next.next = head;
return reverseRest;
}
}