[Leetcode] Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Solution:

1. 先遍历一边list找到有几个要reverse的group。

2. group内部的reverse总共只用3个pointer:pre, cur, move的方法!

注意:  ListNode的reverse还需要再练习

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode reverseKGroup(ListNode head, int k) {
14         if(head==null)
15             return head;
16         int reverseTimes=getLength(head)/k;
17         ListNode dummy=new ListNode(-1);
18         dummy.next=head;
19         ListNode pre=dummy;
20         ListNode cur=dummy.next;
21         while(reverseTimes!=0){
22             reverseTimes--;
23             for(int i=0;i<k-1;++i){
24                 ListNode move=cur.next;
25                 cur.next=move.next;
26                 move.next=pre.next;
27                 pre.next=move;
28             }
29             pre=cur;
30             cur=cur.next;
31         }
32         return dummy.next;
33     }
34 
35     private int getLength(ListNode head) {
36         // TODO Auto-generated method stub
37         ListNode cur=head;
38         int cnt=0;
39         while(cur!=null){
40             cnt++;
41             cur=cur.next;
42         }
43         return cnt;
44     }
45 }
原文地址:https://www.cnblogs.com/Phoebe815/p/4104801.html