LeetCode-206. Reverse Linked List

问题描述

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example:

1
2
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

解答

解法一:迭代
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
/*
* @Description: 反转链表
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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}
*/
const reverseList = function(head) {
let pre = null
let cur = head
while (cur !== null) {
let temp = cur.next
cur.next = pre
pre = cur
cur = temp
}
return pre
}
解法二:递归
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
/*
* @Description: 反转链表
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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}
*/
const 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
}