25. Reverse Nodes in k-Group

25. 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.

k is a positive integer and is less than or equal to the length of the linked 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  * 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     
15     //上一题其实是k=2的情况
16     
17     if(k === 1){
18         return head;
19     }
20     
21     var temp = head;
22     
23     //举例来说,当k=2时,那我们需要判断head和head.next是不是null,因为这种表示最多1个节点,小于2。
24     for(var i = 1;i < k;i++){
25        
26          if(temp === null || temp.next === null){
27              return head;
28          }
29          
30         temp = temp.next;
31         
32     }
33     
34     //关于满足k长度的节点链,我们用头插法实现反转
35     //比如 1->2->3->4->5 k=4
36     
37     //(1) 0->2->1->3->4->5  pre指向val==1的node,cur指向val==2的node,next指向val==3的node
38     //(2) 0->3->2->1->4->5
39     //.....
40     
41     
42     var newHead = new ListNode(0);
43      newHead.next = head;
44     
45     var pre = newHead.next;
46     var cur  = pre.next;
47     var next = cur.next;
48     
49     for(var j = 1;j < k; j++){
50         
51         var tempHead = newHead.next;
52         
53         newHead.next = cur;
54        
55         cur.next = tempHead;
56         
57         
58         
59         pre.next = next;
60         
61         cur =  pre.next;
62         
63         next = cur !==null ? cur.next:null;
64                
65     }
66     
67     next = pre.next;
68     pre.next = reverseKGroup(next,k);
69     
70     return newHead.next;
71     
72     
73 };

 

posted @ 2017-10-18 11:21  hdu胡恩超  阅读(126)  评论(0编辑  收藏  举报