首页 > 其他 > 详细

Reverse Nodes in k-Group

时间:2014-05-05 22:45:55      阅读:414      评论:0      收藏:0      [点我收藏+]

Link: http://oj.leetcode.com/problems/reverse-nodes-in-k-group/

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

bubuko.com,布布扣
 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode reverseKGroup(ListNode head, int k) {
14         if (head == null || head.next == null)
15             return head;
16         ListNode pre = new ListNode(0);
17         pre.next = head;
18         head = pre;
19         int index = 1;
20         ListNode cur = pre.next;
21         ListNode post = cur.next;
22         //before execution, we need to check if there‘s enough element
23         while (enoughElement(cur, k)) {
24             while (index < k) {
25                 ListNode temp = post.next;
26                 post.next = pre.next;
27                 cur.next = temp;
28                 pre.next = post;
29                 post = temp;
30                 index++;
31             }
32             //after the reverse operation,we need to initial
33             //the parameter
34             index = 1;
35             pre = cur;
36             cur = cur.next;
37             //note the cur may be null
38             if (cur != null) {
39 
40                 post = cur.next;
41             }
42         }
43         return head.next;
44 
45     }
46 
47     public boolean enoughElement(ListNode head, int k) {
48         int count = 0;
49         //note the head could be null, then we cannot use head.next
50         while (head != null) {
51             head = head.next;
52             count++;
53         }
54         if (count < k)
55             return false;
56         return true;
57 
58     }
59 }
bubuko.com,布布扣

 

For the basic idead of the algorithm, please refer to http://www.cnblogs.com/Altaszzz/p/3704780.html

 

 

Reverse Nodes in k-Group,布布扣,bubuko.com

Reverse Nodes in k-Group

原文:http://www.cnblogs.com/Altaszzz/p/3704781.html

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