从零开始刷力扣(2)——206.反转链表

114 阅读1分钟

分类:链表

题目描述

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

提示:

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

image.png

输入:[1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

image.png

输入:[1,2]
输出:[2,1]

题解:

思路1

通过递归,把当前节点依次移至末尾节点

代码实现

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
const reverseList = function(head) { 
    if (head == null || head.next == null) return head; 
    let last = reverseList(head.next); 
    head.next.next = head;
    head.next = null; 
    return last; 
};

运行结果

image.png

思路2:通过迭代的方式不断把当前节点移至末尾

代码实现

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
 const reverseList = function (head) { 
     let prev = null, current = head; 
     while (current) {
         const next = current.next; 
         current.next = prev; 
         prev = current;
         current = next;
     } 
     return prev; 
 };

运行结果

image.png