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

Leetcode Reverse Nodes in k-Group

2015-05-10 16:00 337 查看

题目:

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


分析:

1. 首先要判断以当前节点之后的链表的节点个数是否大于等于k,如果满足,进行第2步,否则,直接返回。这里写一个辅助函数isValid(ListNode head, int k)来进行判断比较方便。

2. 判断过后如果需要进行反转,则当前节点和之后的k-1个节点进行反转。由于表头会发生改变,因此使用dummy node比较方便。

举一个例子说明上面的算法:   1 --> 2 --> 3 --> 4      k = 2

1. 首先判断isValid(head, 2),有效,所以开始对1,2这一对节点进行反转。

dummy node   -->   1   -->   2   -->   3   -->   4    -->    null

     pre               start                   end

2. 在反转的过程中,需要几个指针,pre = dummy,这个指针需要记录一组反转节点之前的节点,从而使一组反转的节点整体转过来,start指针和pre节点的目的类似,只不过是使反转组的第一个节点转到最后一个,end指针则用来把反转组的节点和后面的节点连接起来。

dummy node   -->   2   -->   1   -->   3   -->   4    -->    null

                                       pre       start                      end

3. 1和2反转之后,三个指针都向后推,再对3和4进行反转。

Java代码实现:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head==null || head.next==null)
return head;

ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode node = head;
while(isValid(node, k) && node!=null)
{
ListNode start = node;
ListNode temp = node.next;
ListNode end = temp;
for(int i=1;i<k;i++)
{
end = temp.next;
temp.next = node;
node = temp;
temp = end;
}
pre.next = node;
start.next = end;
pre = start;
node = end;
}

return dummy.next;
}
private boolean isValid(ListNode head, int k)
{
ListNode node = head;
for(int i=0;i<k;i++)
{
if(node==null)
return false;
node = node.next;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息