首页 > 其他 > 详细

[Leetcode] Reverse Nodes in k-Group

时间:2015-12-03 21:08:04      阅读:277      评论:0      收藏:0      [点我收藏+]

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

 

 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 ListNode reverseKGroup(ListNode head, int k) {
11         if(k <= 0) {
12             throw new IllegalArgumentException("k <= 0");
13         }
14         if(k == 1) {
15             return head;
16         }
17         
18         ListNode dummy1 = new ListNode(0);                 // head node of the original list
19         ListNode dummy2 = new ListNode(0), tail2 = null;   // head node of the working list for reversing
20         ListNode dummy3 = new ListNode(0), tail3 = dummy3; // head node of resulting list
21         dummy1.next = head;
22         dummy2.next = null;
23         dummy3.next = null;
24         
25         int i = 1; // the nth node in the original list
26         while(dummy1.next != null) {
27             // Remove from the original list
28             ListNode curr = dummy1.next;
29             dummy1.next = curr.next;
30             
31             // Add to the head of reversed list
32             curr.next = dummy2.next;
33             dummy2.next = curr;
34             
35             if(i % k == 0) { // a group of k nodes has been reversed
36                 tail3.next = dummy2.next;
37                 dummy2.next = null;
38                 tail3 = tail2;
39             }else if(i % k == 1) {
40                 tail2 = curr;
41                 tail2.next = null;
42             }
43             i++;
44         }
45         
46         while(dummy2.next != null) {
47             ListNode p = dummy2.next;
48             dummy2.next = p.next;
49             p.next = tail3.next;
50             tail3.next = p;
51         }
52         
53         return dummy3.next;
54     }
55 }

 

[Leetcode] Reverse Nodes in k-Group

原文:http://www.cnblogs.com/seagoo/p/5017410.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!