-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse_Nodes_in_k_Group.java
More file actions
57 lines (54 loc) · 1.45 KB
/
Reverse_Nodes_in_k_Group.java
File metadata and controls
57 lines (54 loc) · 1.45 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
package com.leet_code;
import java.util.ArrayList;
import java.util.List;
public class Reverse_Nodes_in_k_Group {
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; }
}
// public ListNode reverseKGroup(ListNode head, int k) {
//
// }
public ListNode reverseBetween(ListNode head, int left, int right) {
if (left == right) {
return head;
}
ListNode current = head;
ListNode prev = null;
for (int i = 0; current != null && i < left - 1; i++) {
prev = current;
current = current.next;
}
ListNode last = prev;
ListNode newEnd = current;
ListNode next = current.next;
for (int i = 0; current != null && i < right - left + 1; i++) {
current.next = prev;
prev = current;
current = next;
if (next != null) {
next = next.next;
}
}
if (last != null) {
last.next = prev;
} else {
head = prev;
}
newEnd.next = current;
return head;
}
public ListNode isk(ListNode s,int k){
while(k>1 && s.next!=null){
s=s.next;
k--;
}
if (k == 1) {
return s;
}
return null;
}
}