-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path206.反转链表.js
44 lines (40 loc) · 928 Bytes
/
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
/*
* @lc app=leetcode.cn id=206 lang=javascript
*
* [206] 反转链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
// 方法 1 通过新增链表
// let current = head;
// let previous = null;
// while(current) {
// const node = current.next;
// current.next = previous;
// previous = current;
// current = node;
// }
// return previous;
// 方法 2 通过递归实现
if (head == null) return null;
const reverse = (head) => {
if (head === null || head.next === null) return head;
const node = reverse(head.next);
head.next.next = head;
head.next = null;
return node;
}
return reverse(head)
};
// @lc code=end