标签:
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.
/** * 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 prev = null; var now = head; var next = head.next; var iprev = null; var inext = null; var ihead = null; var itail = null; var s = 1; var newhead = false; while (now) { if (s >= m && s <= n) { if (s == m) { itail = now; iprev = prev; } if (s == n) { ihead = now; inext = next; } now.next = prev; prev = now; now = next; if (now) { next = now.next; } if (s == n) { if (!iprev) { head = ihead; } else { iprev.next = ihead; } itail.next = inext; break; } } else { prev = now; now = next; if (now) { next = now.next; } } s++; } return head; };
代码比较丑,用了大量的零时变量来存东西,思路跟翻转整个链表那题如出一辙。简述一下思路就是:用三指针prev, now, next 遍历链表,当到达指定范围后开始翻转操作,并顺便记录翻转那部分的头和尾(ihead, itail)还有相应接头部分的指针(iprev, inext)以便最后翻转完了以后把两部分接起来。特别注意的是链表的头可能会被改变。
[LeetCode] Reverse Linked List II
标签:
原文地址:http://www.cnblogs.com/agentgamer/p/4908580.html