码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Reverse Nodes in k-Group

时间:2015-05-30 07:02:44      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

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

https://leetcode.com/problems/reverse-nodes-in-k-group/

 

 


 

 

第一遍写得比较乱,而且开了map。

思路就是用一组指针指向结果链表,再用一组指针指向目前的反转的链表。

 1 /**
 2  * Definition for singly-linked list.
 3  * function ListNode(val) {
 4  *     this.val = val;
 5  *     this.next = null;
 6  * }
 7  */
 8 /**
 9  * @param {ListNode} head
10  * @param {number} k
11  * @return {ListNode}
12  */
13 var reverseKGroup = function(head, k) {
14     var res = new ListNode(-1);
15     var resTail = res;
16     var h = null;
17     var t = null;
18     var map = [];
19     var count = 0;
20     while(head){
21         if(count === 0){
22             h = t = head;
23             head = head.next;
24             t.next = null;
25             map[count] = h;
26             count++;
27         }else if(count === k){
28             if(res.next === null){
29                 res.next = h;
30             }
31             resTail.next = h;
32             resTail = t;
33             count = 0;
34             map = [];
35         }else{
36             var tmp = head.next;
37             head.next = h;
38             h = head;
39             map[count] = h;
40             head = tmp;
41             count++;
42             
43         }
44     }
45 
46     if(map.length === k){
47         resTail.next = h;
48     }else{
49         for(var i in map){
50             resTail.next = map[i];
51             resTail = map[i];
52         }  
53         resTail.next = null;
54     }
55     return res.next;
56     
57 };

 

 

[LeetCode][JavaScript]Reverse Nodes in k-Group

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4539713.html

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