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

LeetCode进阶之路(Reverse Nodes in k-Group)

2016-07-27 22:40 441 查看
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

题目:给出一个链表和一个整数K,将链表以K个划分,并倒序,最后不满K个节点不变化位置。
思路:首先想到是将该链表以K个划分,并将每部分倒序后组合起来。一个链表倒序首先想到也是将节点放到数组里,这样就变的很熟悉,但是题目希望我们能熟悉链表指针,所以这里还是思考了使用指针来实现倒序的方法。
链表倒序:思路是每遍历一次,就把后一位移到第一位,直到完成。

public ListNode reverse(ListNode node) {
ListNode p1,p2 = null;
p1 = node;
while(node.next != null) {
p2 = node.next;
node.next = p2.next;
p2.next = p1;
p1 = p2;
}
return p2;
}
遍历节点,按K个取值
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null) {
return null;
}

if(head.next == null ||k==1) {
return head;
}

ListNode p1 = head;
ListNode p2 = new ListNode(-1);
ListNode p = p2;
while(p1 != null) {

ListNode p4 = new ListNode(-2);
ListNode p3 = p4;
int count = 0;
while(count < k) { //取出K个节点,倒序后放到p2链表
count++;
p3.next = p1;
p3 = p3.next;
if(p1.next == null) {//最后一个节点时结束循环,若此时count < k,就直接加到p2后面;若count = k,则执行倒序后覆盖
p.next = p4.next;
p1 = p1.next;
break;
}
p1 = p1.next;//p1指针一步步往后遍历

}
if(count == k) {
p3.next = null;//k个节点之后置为null,只倒序K个节点。
p.next = reverse(p4.next);
}
while(p.next != null) {
p = p.next;//每次加上k个节点,就把指针移到p2结尾,等待下一组节点
}
}
return p2.next;
}



种一棵树最好的时间是十年前,其次是现在!

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