-
Notifications
You must be signed in to change notification settings - Fork 4
/
206.反转链表.js
55 lines (51 loc) · 1.02 KB
/
206.反转链表.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
/*
* @lc app=leetcode.cn id=206 lang=javascript
*
* [206] 反转链表
*/
// 题目:https://leetcode-cn.com/problems/reverse-linked-list/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
// 1、迭代
// 迭代1
// var reverseList = function(head) {
// let prev = null;
// let cur = head;
// while(cur) {
// const next = cur.next;
// cur.next = prev;
// prev = cur;
// cur = next;
// }
// return prev;
// };
// 迭代2:解构赋值
var reverseList = function(head) {
let [prev, curr] = [null, head];
while(curr != null) {
// 解构复制
[curr.next, prev, curr] = [prev, curr, curr.next];
}
return prev
};
// 递归
var reverseList = function(head) {
if(head == null || head.next == null) {
return head
}
let newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
// @lc code=end