码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Reverse Nodes in k-Group

时间:2014-11-18 06:52:58      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   sp   for   div   on   

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. 先遍历一边list找到有几个要reverse的group。

2. group内部的reverse总共只用3个pointer:pre, cur, move的方法!

注意:  ListNode的reverse还需要再练习

 

 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)
15             return head;
16         int reverseTimes=getLength(head)/k;
17         ListNode dummy=new ListNode(-1);
18         dummy.next=head;
19         ListNode pre=dummy;
20         ListNode cur=dummy.next;
21         while(reverseTimes!=0){
22             reverseTimes--;
23             for(int i=0;i<k-1;++i){
24                 ListNode move=cur.next;
25                 cur.next=move.next;
26                 move.next=pre.next;
27                 pre.next=move;
28             }
29             pre=cur;
30             cur=cur.next;
31         }
32         return dummy.next;
33     }
34 
35     private int getLength(ListNode head) {
36         // TODO Auto-generated method stub
37         ListNode cur=head;
38         int cnt=0;
39         while(cur!=null){
40             cnt++;
41             cur=cur.next;
42         }
43         return cnt;
44     }
45 }

 

[Leetcode] Reverse Nodes in k-Group

标签:des   style   blog   io   color   sp   for   div   on   

原文地址:http://www.cnblogs.com/Phoebe815/p/4104801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!