File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * public class ListNode {
4+ * int val;
5+ * ListNode next;
6+ * ListNode() {}
7+ * ListNode(int val) { this.val = val; }
8+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+ * }
10+ */
11+ class Solution {
12+ public ListNode reverseKGroup(ListNode head, int k) {
13+ int count =0;
14+ ListNode dummy = new ListNode();
15+ dummy.next = head;
16+
17+ ListNode temp = dummy;
18+
19+ while(temp.next!=null){
20+ temp = temp.next;
21+ count++;
22+ }
23+ temp = dummy;
24+ while(temp.next!=null){
25+ if(count<k) break;
26+ int nodes = k-1;
27+ ListNode tempnext = temp.next;
28+ ListNode first = temp.next;
29+ ListNode second = first.next;
30+
31+ while(nodes-- > 0){
32+ ListNode next = second.next;
33+ second.next = first;
34+ first = second;
35+ second = next;
36+ }
37+ count-=k;
38+ temp.next = first;
39+ tempnext.next = second;
40+ temp = tempnext;
41+
42+ }
43+ return dummy.next;
44+ }
45+ }
You can’t perform that action at this time.
0 commit comments