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

[Leetcode] Reverse Nodes in k-Group

2015-12-03 19:50 519 查看
Problem:

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


/**
* 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(k <= 0) {
throw new IllegalArgumentException("k <= 0");
}
if(k == 1) {
return head;
}

ListNode dummy1 = new ListNode(0);                 // head node of the original list
ListNode dummy2 = new ListNode(0), tail2 = null;   // head node of the working list for reversing
ListNode dummy3 = new ListNode(0), tail3 = dummy3; // head node of resulting list
dummy1.next = head;
dummy2.next = null;
dummy3.next = null;

int i = 1; // the nth node in the original list
while(dummy1.next != null) {
// Remove from the original list
ListNode curr = dummy1.next;
dummy1.next = curr.next;

// Add to the head of reversed list
curr.next = dummy2.next;
dummy2.next = curr;

if(i % k == 0) { // a group of k nodes has been reversed
tail3.next = dummy2.next;
dummy2.next = null;
tail3 = tail2;
}else if(i % k == 1) {
tail2 = curr;
tail2.next = null;
}
i++;
}

while(dummy2.next != null) {
ListNode p = dummy2.next;
dummy2.next = p.next;
p.next = tail3.next;
tail3.next = p;
}

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