-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinkedList.java
More file actions
69 lines (56 loc) · 1.5 KB
/
ReverseLinkedList.java
File metadata and controls
69 lines (56 loc) · 1.5 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
65
66
67
68
69
package leetcode.practice;
import java.io.IOException;
public class ReverseLinkedList {
public static void main(String args[]) throws IOException
{
LinkedList llist = new LinkedList();
for (int i = 1; i < 10; i++)
{
llist.addToTheLast(new Node(i));
}
llist.printList();
llist.head = new ReverseLinkedList().reverseListIterative(llist.head);
llist.printList();
llist.head = new ReverseLinkedList().reverseListRecursive(llist.head);
llist.printList();
llist.head = new ReverseLinkedList().reverseListIterative(llist.head, 2);
llist.printList();
}
private Node reverseListRecursive(Node head) {
if (head == null || head.next == null)
return head;
Node revesedNode = reverseListRecursive(head.next);
head.next.next = head;
head.next = null;
return revesedNode;
}
private Node reverseListIterative(Node head) {
Node prev = null;
Node next = null;
Node curr = head;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
private Node reverseListIterative(Node head, int k) {
Node prev = null;
Node next = null;
Node curr = head;
int count = 0;
while (curr != null && count < k) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
count++;
}
if(next != null) {
head.next = reverseListIterative(next, k);
}
return prev;
}
}