-
Notifications
You must be signed in to change notification settings - Fork 6
/
ReverseLinkedList.java
56 lines (42 loc) · 1.23 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
package com.shivaprasad.january.day9;
//Note: For Linked List problems, Just focus on method code because creating Linked List for every problem is a hectic task,
//and we don't need to worry about it.
//Problem Link: https://leetcode.com/problems/reverse-linked-list/
public class ReverseLinkedList {
class ListNode
{
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
//Iterative Solution
public ListNode reverseList(ListNode head) {
if(head == null)
return null;
ListNode prevNode = null;
while(head!=null)
{
ListNode temp = head.next;
head.next = prevNode;
prevNode = head;
head = temp;
}
return prevNode;
//T.C: O(n)
//S.C: O(1)
}
//Recursive Solution
/*public ListNode reverseList(ListNode head) {
return reverseRecursivly(head,null);
}
public ListNode reverseRecursivly(ListNode head, ListNode prevNode)
{
if(head == null)
return prevNode;
ListNode temp = head.next;
head.next = prevNode;
return reverseRecursivly(temp,head);
//T.C: O(n)
//S.C: O(n)
} */
}