-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
46 lines (43 loc) · 887 Bytes
/
index.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
const { make_list_node, ListNode } = require('../utils');
const head = make_list_node([1,2,3,4,5]);
/**
* 迭代
*
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
if (!head){
return head;
}
let result = new ListNode(head.val);
head = head.next;
while(head) {
const current_node = new ListNode(head.val);
current_node.next = result;
result = current_node;
head = head.next;
}
return result;
};
/**
* 递归
*
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
if (!head || !head.next){
return head;
}
const p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
};
let test = reverseList(head);
while (test) {
console.log(test.val);
test = test.next;
}
console.log(head);