学习笔记:剑指 Offer 24. 反转链表

52 阅读1分钟

题目描述

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

题目分析

链表反转,遍历链表,每次遍历将后一个元素向前移动一位

代码实现

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
// head = [1, 3, 5]
const reverseLinked = function(head) {
    // head == null 和 head === null || head === undefined 等价
    if (head == null) {
        return null
    }
    let previous = null;
    let next = null;
    let current = head;
    while(current != null) {
        next = current.next
        current.next = previous
        previous = current
        current = next
    }
    return previous
}

代码分析

  • 判断传参 head 是否为空, 为空返回 null
  • 定义变量,previous表示前一个元素, next表示下一个元素, current表示当前元素
  • 遍历current:内部实现其实就是进行元素替换
    1. 第一轮循环得到的结果: next => 3, 5; previous => 1; current => 3,5;
    2. 第二轮循环得到的结果: next => 5; previous => 3,1; current => 5;
    3. 第三轮循环得到的结果: next => null; previous => 5,3,1; current => null;
  • 返回previous结果

题目来源

剑指 Offer 24. 反转链表