反转链表的三种方法:栈结构、循环、递归

class ListNode {

    val: number

    next: ListNode | null

    constructor(val?: number, next?: ListNode | null) {

        this.val = (val === undefined ? 0 : val)

        this.next = (next === undefined ? null : next)

    }

}

// 方法1:使用栈结构

function reverseList(head:ListNode|null){

        //设置边界条件

        if(!head||!head.next) return head

        方法一:使用栈结构反转链表

        let arr:ListNode[]=arr

        while(head){

                arr.push(head)

                head = head.next

        }

        let newNode = arr.pop()!  // 初始化newNode

        let current = newNode // 存储当前节点

        while(arr.length){

                   current.next = arr.pop() // 让当前的节点 指向数组列表中的 倒数第二个节点

                    current = current.next    // 取出倒数第二个节点 继续循环 直到列表的长度为0

        }

        // 但是这里要注意 当取到第一个节点的时候 要将第一个节点的next 指向null 这样就不会形成一个闭环

        current.next = null

        return newNode

}

// 方法二:使用循环

function reverseList(head:ListNode|null){

        //设置边界条件

        if(!head||!head.next) return head

        方法一:使用栈结构反转链表

        let newNode = null // 初始化一个链表  让他一开始指向null

           let   current = head //存储当前的节点

        while(head){

               current = head.next //存储当前的节点

                head.next = newNode // 当当前节点的next 指向newNode

                newNode = head // 改变newNode的指向 指向head  为了让下一次再去指向这个节点

                head = current // 给head重新赋值 再取出这个节点

}      

        return newNode

}

// 方法三:使用递归 取出倒数第二个节点 ;从而拿到最后一个节点 修改最后一个节点的指向 指向倒数第二个节点;让倒数第二个节点 指向null ;缩短了原来的链表

function reverseList(head:ListNode|null){

        //设置边界条件

        if(!head||!head.next) return head

        let newNode = reverseList(head.next)

        head.next.next=head

        head.next = null

            

        return newNode

}

let node = new ListNode(1)

node.next = new ListNode(2)

node.next.next = new ListNode(3)

node.next.next.next = new ListNode(4)

let newNode = reverseList(node)

// 打印操作后的链表的值

let arr: number[] = []

let newnode: ListNode | null = newNode

while (newnode) {

    arr.push(newnode.val)

    newnode = newnode.next

}

console.log(arr);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值