[LeetCode][JavaScript]Reverse Linked List II

Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

https://leetcode.com/problems/reverse-linked-list-ii/

 

 


 

 

翻转从m到n的链表。

翻转的操作还是和上一题一样:http://www.cnblogs.com/Liok3187/p/4540490.html

 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} m
11  * @param {number} n
12  * @return {ListNode}
13  */
14 var reverseBetween = function(head, m, n) {
15     var res = new ListNode(-1), subHead = res, count = 1;
16     res.next = head;
17     while(count !== m){
18         subHead = head;
19         head = head.next;
20         count++;
21     }
22     var subTail = head, tmp;
23     while(count !== n + 1){
24         tmp = head.next;
25         head.next = subHead.next;
26         subHead.next = head;
27         head = tmp;
28         count++;
29     }
30     subTail.next = head;
31     return res.next;
32 };

 

 

 

posted @ 2015-10-02 16:21  `Liok  阅读(227)  评论(0编辑  收藏  举报