[编程题] 反转单链表

链表结构

class ListNode {
    value: number
    next: ListNode | null

    constructor(value: number, next: ListNode | null) {
        this.value = value
        this.next = next
    }
}

const node6 = new ListNode(6, null)
const node5 = new ListNode(5, node6)
const node4 = new ListNode(4, node5)
const node3 = new ListNode(3, node4)
const node2 = new ListNode(2, node3)
const node1 = new ListNode(1, node2)

console.log(node1) // 1 2 3 4 5 6

递归反转链表

function reverseLinkedlist(head: ListNode | null): ListNode | null {
    if (head === null || head.next === null) {
        return head
    }
    const prev = reverseLinkedlist(head.next)
    head.next.next = head
    head.next = null
    return prev
}

console.log(reverseLinkedlist(node1)) // 6 5 4 3 2 1
posted @ 2022-09-13 20:14  toddforsure  阅读(8)  评论(0)    收藏  举报