-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathreverse-nodes-in-k-groups.java
More file actions
81 lines (63 loc) · 1.77 KB
/
reverse-nodes-in-k-groups.java
File metadata and controls
81 lines (63 loc) · 1.77 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
// Question - 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) {
int size=size(head);
int iter=size/k;
int l,r;
int i=0;
while (i!=iter) {
l=k*i;
r=l+(k-1);
while (l<r) {
ListNode left=getAt(head,l);
ListNode right=getAt(head,r);
int temp=left.val;
left.val=right.val;
right.val=temp;
l++;
r--;
}
i++;
}
return head;
}
static ListNode getAt(ListNode head, int ind) {
if (ind==0) {
return head;
} else if (ind==size(head)-1) {
ListNode temp=head;
while (temp.next!=null) {
temp=temp.next;
}
return temp;
} else {
ListNode temp=head;
int i=0;
while (i<ind) {
temp=temp.next;
i++;
}
return temp;
}
}
static int size(ListNode head) {
ListNode temp=head;
int cnt=0;
while (temp!=null) {
cnt++;
temp=temp.next;
}
return cnt;
}
}
// Submission - https://leetcode.com/submissions/detail/526062059/