Skip to content
On this page

206. 反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:
输入:head = [1,2]
输出:[2,1]

示例 3:
输入:head = []
输出:[]

提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000

javascript
/**
 * 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) {
  if (!head || !head.next) return head
  const last = reverseList(head.next)
  head.next.next = head
  head.next = null
  return last
}

// 解法二
var reverseList = function (head) {
  if (!head || !head.next) return head
  const stack = []
  let lst = new ListNode(),
    last = lst
  while (head) {
    stack.push(head)
    head = head.next
  }
  while (stack.length > 0) {
    lst.next = stack.pop()
    lst = lst.next
  }
  lst.next = null
  return last.next
}

// test
function ListNode(val) {
  this.val = val
  this.next = null
}

var list = new ListNode(1)
var list1 = new ListNode(2)
var list2 = new ListNode(3)
var list3 = new ListNode(4)
var list4 = new ListNode(5)
list.next = list1
list1.next = list2
list2.next = list3
list3.next = list4

console.log(reverseList(list))