【路飞】算法-反转链表

100 阅读1分钟

题目要连接 LeetCode: leetcode-cn.com/problems/re…

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

示例 示例1

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

示例2

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

示例3

输入: head = []
输出: []

解题思路 1、定义指针pre,指向null,定义指针cur,指向头节点;定义指针next,指向头节点的下一位 2、将cur指向pre 3、移动指针pre到指针cur的位置 4、移动cur到next的位置 5、重复2,3,4

注:pre指向的就是翻转过后的链表的头节点;cur指向的是未翻转部分的头节点,next是未翻转头节点的下一位

代码实现

/**
 * 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) return head;
    let pre = null;
    let cur = head;
    let next = head.next;
    while(cur){
        cur.next = pre;
        pre = cur;
        (cur = next) && (next = next.next);  // 短路原则
    }
    return pre;
};