反转链表

新建一个头节点,遍历链表将所有节点依次插入到新的头节点后面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 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) {
let newHead = new ListNode();
let cur = head;
while (cur) {
// 插入到newHead之后
const next = cur.next; // 保存cur.next
cur.next = newHead.next;
newHead.next = cur;
cur = next;
}
return newHead.next;
};

本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。