1
+ /*
2
+ Author: Andy, nkuwjg@gmail.com
3
+ Date: Jan 18, 2015
4
+ Problem: Reverse Nodes in k-Group
5
+ Difficulty: Hard
6
+ Source: https://oj.leetcode.com/problems/reverse-nodes-in-k-group/
7
+ Notes:
8
+ Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
9
+ If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
10
+ You may not alter the values in the nodes, only nodes itself may be changed.
11
+ Only constant memory is allowed.
12
+ For example,
13
+ Given this linked list: 1->2->3->4->5
14
+ For k = 2, you should return: 2->1->4->3->5
15
+ For k = 3, you should return: 3->2->1->4->5
16
+
17
+ Solution: ...
18
+ */
19
+
20
+ /**
21
+ * Definition for singly-linked list.
22
+ * public class ListNode {
23
+ * int val;
24
+ * ListNode next;
25
+ * ListNode(int x) {
26
+ * val = x;
27
+ * next = null;
28
+ * }
29
+ * }
30
+ */
31
+ public class Solution {
32
+ public ListNode reverseKGroup (ListNode head ,int k ) {
33
+ if (k <=1 )return head ;
34
+ int T =GetLength (head ) /k ;
35
+ ListNode dummy =new ListNode (0 ),cur =head ,ins =dummy ;
36
+ dummy .next =head ;
37
+ while ((T --) !=0 ) {
38
+ for (int i =0 ;i <k -1 ; ++i ) {
39
+ ListNode move =cur .next ;
40
+ cur .next =move .next ;
41
+ move .next =ins .next ;
42
+ ins .next =move ;
43
+ }
44
+ ins =cur ;
45
+ cur =cur .next ;
46
+ }
47
+ return dummy .next ;
48
+ }
49
+ public int GetLength (ListNode head ) {
50
+ int length =0 ;
51
+ while (head !=null ) {
52
+ head =head .next ;
53
+ length ++;
54
+ }
55
+ return length ;
56
+ }
57
+ }