forked from rising-entropy/Leetcode-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse_K_Groups.java
91 lines (85 loc) · 2.21 KB
/
Reverse_K_Groups.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
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
86
87
88
89
90
91
/**
* 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; }
* }
*/
class Solution {
public static void main(String[] args) {
insertion(1);
insertion(2);
insertion(3);
insertion(4);
insertion(5);
}
static Node ROOT;
static class Node {
Node NEXT;
int data;
Node(int d) {
data = d;
NEXT = null;
}
}
static void insertion(int item) {
// LinkedList list = new LinkedList();
if (ROOT == null) {
ROOT = new Node(item);
System.out.println(item + " inserted");
return;
}
Node TEMP = ROOT;
while (TEMP.NEXT != null) {
TEMP = TEMP.NEXT;
}
TEMP.NEXT = new Node(item);
System.out.println(item + " inserted");
}
static void traverse() {
Node TEMP = ROOT;
while (TEMP.NEXT != null) {
System.out.print(TEMP.data + " --->");
TEMP = TEMP.NEXT;
}
System.out.println(TEMP.data + " --->");
}
public Node reverseKGroup(Node head, int k) {
int node_size = 0;
Node temp = head;
while(temp != null){
temp = temp.next;
node_size++;
}
int total_count = node_size/k;
System.out.println(total_count);
temp = head;
Node first = head;
int count = 0;
while(total_count != count){
int f_count = 1;
int t_count = k;
int value = k-1;
while(value > 0){
temp = temp.next;
value--;
}
while(f_count < t_count){
System.out.println(f_count);
int t = first.val;
first.val = temp.val;
temp.val = t;
f_count++;
t_count--;
}
first = temp.next;
temp = temp.next;
count++;
}
System.out.println(head.val);
return head;
}
}