-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path206_reverse-linked-list.js
More file actions
47 lines (46 loc) · 881 Bytes
/
Copy path206_reverse-linked-list.js
File metadata and controls
47 lines (46 loc) · 881 Bytes
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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
let prev = null, curr = head
while (curr) {
let next = curr.next
curr.next = prev // 改变指针
prev = curr
curr = next
}
return prev
}
// test tools
function ListNode(val) {
this.val = val;
this.next = null;
}
function printLinkList(head) {
let pointer = head, arr = []
while (pointer) {
arr.push(pointer.val)
pointer = pointer.next
}
arr.push('NULL')
console.log(arr.join(' -> '))
}
// test case init
let head = new ListNode(1)
let pointer = head
for (let i = 2; i < 6; ++i) {
pointer.next = new ListNode(i)
pointer = pointer.next
}
printLinkList(head)
// test
head = reverseList(head)
printLinkList(head)