-
Notifications
You must be signed in to change notification settings - Fork 87
/
Create Reverse_Nodes_in_k-Group.java
88 lines (83 loc) · 2.14 KB
/
Create Reverse_Nodes_in_k-Group.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
// problem link -> https://leetcode.com/problems/reverse-nodes-in-k-group/
/**
* 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 ListNode reverseKGroup(ListNode head, int k) {
MyLinkedList given = new MyLinkedList();
MyLinkedList prev = null;
while(head != null){
given.addLast(head.val);
head = head.next;
}
while(given.size > 0){
MyLinkedList curr = new MyLinkedList();
if(given.size >= k){
for(int i = 0; i < k; i++){
curr.addFirst(given.getFirst());
given.removeFirst();
}
} else {
int os = given.size;
for(int i = 0; i < os; i++){
curr.addLast(given.getFirst());
given.removeFirst();
}
}
if(prev == null){
prev = curr;
} else {
prev.tail.next = curr.head;
prev.tail = curr.tail;
prev.size += curr.size;
}
}
return prev.head;
}
}
class MyLinkedList {
ListNode head;
ListNode tail;
int size;
public void addFirst(int val) {
ListNode node = new ListNode(val);
if(size == 0){
head = tail = node;
size++;
return;
}
node.next = head;
head = node;
size++;
}
public void addLast(int val) {
ListNode node = new ListNode(val);
if(size == 0) {
head = tail = node;
size++;
return;
}
tail.next = node;
tail = tail.next;
size++;
}
public void removeFirst() {
if(size != 0){
head = head.next;
size--;
}
}
public int getFirst() {
if(size == 0){
return -1;
}
return head.val;
}
}