-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathReverseIterativeLL.java
More file actions
64 lines (60 loc) · 1.57 KB
/
ReverseIterativeLL.java
File metadata and controls
64 lines (60 loc) · 1.57 KB
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
https://leetcode.com/problems/reverse-linked-list/
class Solution {
private int len(ListNode head){
ListNode temp = head;
int counter = 0;
while(temp!=null){
counter++;
temp = temp.next;
}
return counter;
}
private ListNode getNode(int index, ListNode head){
ListNode temp = head;
for(int i = 1; i<=index; i++){
temp = temp.next;
}
return temp;
}
public ListNode reverseList2(ListNode head) {
int i = 0;
int j = len(head)-1;
while(i<j){
ListNode leftNode = getNode(i, head);
ListNode rightNode = getNode(j, head);
int temp = leftNode.val;
leftNode.val = rightNode.val;
rightNode.val = temp;
i++;
j--;
}
return head;
}
public ListNode reverseList(ListNode head) {
if(head == null){
return head;}
// Maintain 3 Pointors
ListNode prev = head;
ListNode current = prev.next;
while(current!=null){
ListNode ahead = current.next;
current.next = prev;
prev = current;
current = ahead;
}
ListNode temp = head;
head = prev;
temp.next= null;
return head;
}
}