-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListDay4.java
More file actions
85 lines (70 loc) · 2.31 KB
/
LinkedListDay4.java
File metadata and controls
85 lines (70 loc) · 2.31 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package linkedlist;
import template.Node;
public class LinkedListDay4 {
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(4);
head.next.next = new Node(3);
head.next.next.next = new Node(2);
head.next.next.next.next = new Node(4);
head.next.next.next.next.next = new Node(2);
head.next.next.next.next.next.next = new Node(5);
// Node reversedLLLKTimes = reverseLinkedListKTimesRange(head, 4);
Node partitionLL = partitionLinkedList(head, 4);
LinkedListBasic.printLinkedList(partitionLL);
}
static Node reverseLinkedListKTimesRange(Node head, int k) {
Node dummy = new Node(-1);
dummy.next = head;
Node prevTail = dummy;
Node currHead = head;
while (currHead != null) {
Node currTail = currHead;
for (int i = 0; i < k - 1; i++) {
if (currTail == null) break;
currTail = currTail.next;
}
if (currTail == null) break;
Node nextHead = currTail.next;
reverseKTimes(currHead, k);
prevTail.next = currTail;
currHead.next = nextHead;
prevTail = currHead;
currHead = nextHead;
}
prevTail.next = currHead;
return dummy.next;
}
static void reverseKTimes(Node node, int k) {
if (node == null || node.next == null) return;
Node prev = null, curr = node;
int count = 0;
while (curr != null && count < k) {
Node next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
count++;
}
}
static Node partitionLinkedList(Node head, int k) {
Node leftHead = new Node(-1);
Node rightHead = new Node(-1);
Node leftTail = leftHead;
Node rightTail = rightHead;
Node curr = head;
while (curr != null) {
if (curr.data < k) {
leftTail.next = curr;
leftTail = curr;
} else {
rightTail.next = curr;
rightTail = curr;
}
curr = curr.next;
}
rightTail.next = null;
leftTail.next = rightHead.next;
return leftHead.next;
}
}