-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathDay_07_ReverseLinkedList.java
58 lines (52 loc) · 1.28 KB
/
Day_07_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
import java.util.* ;
import java.io.*;
/*
Following is the structure of the Singly Linked List.
class LinkedListNode<T>
{
T data;
LinkedListNode<T> next;
public LinkedListNode(T data)
{
this.data = data;
}
}
*/
public class Solution
{
public static LinkedListNode<Integer> reverseLinkedList(LinkedListNode<Integer> head)
{
// Write your code here!
LinkedListNode<Integer> curr=head;
LinkedListNode<Integer> temp=null;
LinkedListNode<Integer> prev=null;
while(curr!=null){
temp=prev;
prev=curr;
curr=curr.next;
prev.next=temp;
}
return prev;
}
}
// Recursive Code
/*
1->2->3->4->N
Assuming that recursive call has already reversed the rest of the node and we have to reverse only initial node.
1->(2<-3<-4<-newHead)
head -> 1
head.next->2
head.next.next=head => 2->1
head.next=null => 2->1->N
Final => N<-1<-2<-3<-4<-newHead
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null)
return head;
ListNode node=reverseList(head.next);
head.next.next=head;
head.next=null;
return node;
}
}