-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreverse-linked-list-ii.js
117 lines (104 loc) · 2.48 KB
/
reverse-linked-list-ii.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/**
* Source: https://leetcode.com/problems/reverse-linked-list-ii/
* Tags: [Linked List]
* Level: Medium
* Title: Reverse Linked List II
* Auther: @imcoddy
* Content: 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}
*/
/**
* Memo: Switch append to tail or insert
* Complex: O(n)
* Runtime: 136ms
* Tests: 44 test cases passed
* Rank: S
* Updated: 2015-06-20
*/
var reverseBetween = function(head, m, n) {
if (!head || !head.next || m === n) return head;
var dummy = new ListNode(null);
var tail = dummy;
var p = head;
var count = 0;
while (p) {
var pnext = p.next;
if (++count >= m && count <= n) {
p.next = tail.next;
tail.next = p;
} else {
while (tail.next) tail = tail.next;
tail.next = p;
tail = tail.next;
tail.next = null;
}
p = pnext;
}
return dummy.next;
};
/**
* Memo: Reserve the middle part then append it to original List
* Complex: O(n)
* Runtime: 132ms
* Tests: 44 test cases passed
* Rank: S
* Updated: 2015-08-09
*/
var reverseBetween = function(head, m, n) {
if (!head || !head.next || m === n) return head;
var dummy = new ListNode(null);
dummy.next = head;
var p = dummy;
var count = 1;
while (++count <= m) p = p.next; // find the previous node to break the list
var tail = p;
var next = p.next;
tail.next = null;
p = next;
var reverse = new ListNode(null);
var tail2 = p;
while (count++ <= 1 + n) {
next = p.next;
p.next = reverse.next;
reverse.next = p;
p = next;
}
tail.next = reverse.next;
tail2.next = p;
return dummy.next;
};
function ListNode(val) {
this.val = val;
this.next = null;
}
var util = require("./util.js");
var should = require('should');
console.time('Runtime');
util.lta(reverseBetween(util.atl([1, 2, 3, 4, 5]), 2, 4)).should.eql([1, 4, 3, 2, 5]);
util.lta(reverseBetween(util.atl([1, 2]), 1, 2)).should.eql([2, 1]);
console.timeEnd('Runtime');