【leetcode】25. 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.

解题分析:

解题思路不难简单,同上一题一样,难点在于每个节点的next域指向问题,只要能在纸上演示一遍就不难做出来。再次强烈建议解答链表的题可以现在纸上把步骤实现一遍。

具体代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10    public static ListNode reverseKGroup(ListNode head, int k) {
11         if(head==null)
12             return null;
13         if(k==1)
14             return head;
15         ListNode pre = new ListNode(Integer.MIN_VALUE);
16         pre.next=head;
17         head=pre;
18         ListNode from=pre.next;
19         ListNode to=from;
20         //while(to!=null&&count<k){
21         //    to=to.next;
22         //    count++;
23         //}
24         while(to!=null){
25             int count=1;
26             while(to!=null&&count<k){
27                 to=to.next;
28                 count++;
29             }
30             if(to==null){
31                 break;
32             }
33             else{
34                 //System.out.println(pre.val+".."+from.val+":"+to.val);
35                 //System.out.println("*******");
36                 pre = fun(pre,from,to);
37                 //System.out.println(pre.val);
38             //    System.out.println("*******");
39                 from=pre.next;
40                 to=from;
41             }
42         }
43         return head.next;
44     }
45     public static ListNode fun(ListNode pre,ListNode from,ListNode to){
46         ListNode post = to.next;
47         to.next=null;
48         ListNode head = from;
49         ListNode current=null;
50         from=from.next;
51         head.next=post;
52         ListNode nPre=head;
53         while(from!=null){
54             current=from;
55             from=from.next;
56             current.next=head;
57             head=current;
58             
59         }
60         pre.next=head;
61         return nPre;
62     }
63     
64 }
原文地址:https://www.cnblogs.com/godlei/p/5642170.html