-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathReverseList.java
67 lines (53 loc) · 1.48 KB
/
ReverseList.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
/*https://leetcode.com/problems/reverse-linked-list/*/
//iterative version
class Solution {
public ListNode reverseList(ListNode head) {
//edge case
if (head == null || head.next == null)
return head;
//three pointer approach
ListNode prev = head;
ListNode curr = head;
ListNode newList = head;
//till we are left with new elements
while (newList != null)
{
//set curr to new element
curr = newList;
//set new element to the next element
newList = curr.next;
//modify the poninter
curr.next = prev;
//move the previous pointer forward
prev = curr;
}
//remove the loop
head.next = null;
//update the head
head = curr;
return head;
}
}
//recursive approach
class Solution {
public ListNode reverseList(ListNode head) {
//edge case
if (head == null || head.next == null)
return head;
//recursion call
head = reverse(head);
return head;
}
public ListNode reverse(ListNode head) {
//last node will be the base case, return it as it is
if (head.next == null)
return head;
/*recursion*/
ListNode newHead = reverse(head.next);
//reverse
head.next.next = head;
head.next = null;
//return
return newHead;
}
}