首页 > 其他 > 详细

Reverse Nodes in k-Group 解答

时间:2015-11-05 23:47:47      阅读:283      评论:0      收藏:0      [点我收藏+]

Question

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

Solution

这道题并不难,但是比较繁琐。思路是两步走:

1. 找出当前要反转的子序列

2. 反转子序列 (类比反转 m - n 那道题)

对要反转的子序列,我们用一头(prev)一尾(end)表示

prev -> 1 -> 2 -> 3 -> 4 -> end

如k=4,在help函数中,我们定义cur = prev.next, then = cur.next 循环结束条件是then != end。最后返回新序列的尾指针,即下一个要反转序列的prev指针,该例子中为4。

 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 (head == null || k == 0 || k == 1) {
12             return head;
13         }
14         ListNode dummy = new ListNode(-1);
15         ListNode prev = dummy;
16         dummy.next = head;
17         int i = 0;
18         while (head != null) {
19             i++;
20             if (i % k == 0) {
21                 prev = reverse(prev, head.next);
22                 head = prev.next;
23             } else {
24                 head = head.next;
25             }
26         }
27         return dummy.next;
28     }
29     
30     private ListNode reverse(ListNode prev, ListNode end) {
31         ListNode cur = prev.next, head = prev.next;
32         ListNode then = cur.next;
33         cur.next = null;
34         ListNode tmp;
35         while (then != end) {
36             tmp = then.next;
37             then.next = cur;
38             cur = then;
39             then = tmp;
40         }
41         prev.next = cur;
42         head.next = end;
43         return head;
44     }
45 }

 

Reverse Nodes in k-Group 解答

原文:http://www.cnblogs.com/ireneyanglan/p/4940982.html

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