site logo

Marico' space

反转链表

算法解析 2024-06-09 23:05:22 196

描述

给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。

数据范围: 0≤n≤1000

要求:空间复杂度 O(1) ,时间复杂度O(n) 。

如当输入链表{1,2,3}时,

经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。

以上转换过程如下图所示:

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param head ListNode类
 * @return ListNode类
 */
function ReverseList(head) {
    if(!head?.next) return head
    let node = head  // 1

    let x = node?.next // 2
    node.next = null
    while(!!x){
        
        let t = x.next // 3
        x.next = node // 2->1
        node = x  // 2
        x = t //3
        console.log('current node: ==> ',node, 'x: ==> ', x)

    }


    console.log(node)

    return node

    
}
module.exports = {
    ReverseList: ReverseList,
};