您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Reverse Linked List II

2015-10-02 16:21 579 查看

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->NULL
, m = 2 and n = 4,

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

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

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

翻转从m到n的链表。

翻转的操作还是和上一题一样:/article/7170929.html

/**
* Definition for singly-linked list.
* function ListNode(val) {
*     this.val = val;
*     this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} m
* @param {number} n
* @return {ListNode}
*/
var reverseBetween = function(head, m, n) {
var res = new ListNode(-1), subHead = res, count = 1;
res.next = head;
while(count !== m){
subHead = head;
head = head.next;
count++;
}
var subTail = head, tmp;
while(count !== n + 1){
tmp = head.next;
head.next = subHead.next;
subHead.next = head;
head = tmp;
count++;
}
subTail.next = head;
return res.next;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: