您的位置:首页 > Web前端 > Node.js

【leetcode】25. Reverse Nodes in k-Group

2016-07-05 00:39 597 查看

题目描述:

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域指向问题,只要能在纸上演示一遍就不难做出来。再次强烈建议解答链表的题可以现在纸上把步骤实现一遍。

具体代码:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public static ListNode reverseKGroup(ListNode head, int k) {
if(head==null)
return null;
if(k==1)
return head;
ListNode pre = new ListNode(Integer.MIN_VALUE);
pre.next=head;
head=pre;
ListNode from=pre.next;
ListNode to=from;
//while(to!=null&&count<k){
//    to=to.next;
//    count++;
//}
while(to!=null){
int count=1;
while(to!=null&&count<k){
to=to.next;
count++;
}
if(to==null){
break;
}
else{
//System.out.println(pre.val+".."+from.val+":"+to.val);
//System.out.println("*******");
pre = fun(pre,from,to);
//System.out.println(pre.val);
//    System.out.println("*******");
from=pre.next;
to=from;
}
}
return head.next;
}
public static ListNode fun(ListNode pre,ListNode from,ListNode to){
ListNode post = to.next;
to.next=null;
ListNode head = from;
ListNode current=null;
from=from.next;
head.next=post;
ListNode nPre=head;
while(from!=null){
current=from;
from=from.next;
current.next=head;
head=current;

}
pre.next=head;
return nPre;
}

}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: