反装单向链表

40 阅读1分钟

以下为Demo,我们主要利用了递归函数的回溯特性

function NodeList(key) {
    this.key = key
    this.next = null
}

class LinkedList {

    constructor() {
        this.head = null
    }

    insert(node) {

        // node.next = this.head
        if(this.head !== null) {
            node.next = this.head
        }

        this.head = node

    }
   

    reverse( p = this.head) {

        if ( p.next ) {
          

            this.reverse(p.next)
            p.next.next = p
            p.next = null 
        } else {
            this.head = p

        }


    }
}

let list = new LinkedList()
let node1 = new NodeList('1')
let node2 = new NodeList('2')
let node3 = new NodeList('3')
let node4 = new NodeList('4')

list.insert(node1)
list.insert(node2)
list.insert(node3)
list.insert(node4)


list.reverse()


console.log(node4)