劍指offer-03從尾到頭打印鏈表

題目描述

輸入一個鏈表,從尾到頭打印鏈表每個節點的值。

代碼

function Node(element) {
    this.element=element;
    this.next=null;
}

function LList() {
    this.head=new Node('head');
    this.find=find;
    this.insert=insert;
    this.display=display;
}

function find(item) {
    var currNode=this.head;
    while(currNode.element != item){
        currNode=currNode.next;
    }
    return currNode;
}

function insert(newElement,item) {
    var newNode = new Node(newElement);
    var current = this.find(item);
    newNode.next=current.next;
    current.next=newNode;
}

function display(){
    var currNode=this.head;
    while(!(currNode.next==null)){
      console.log(currNode.next.element);
        currNode=currNode.next;
    }
}



function printListFromTailToHead(head) {

    var arr=[];
    while(head!=null){
        arr.push(head.element);
        head=head.next;
    }
    return arr.reverse()
}

/*測試*/
var cities=new LList();
cities.insert("Conway","head");
cities.insert("Russellville","Conway");
cities.insert("Alma","Russellville");



console.log(printListFromTailToHead(cities.head.next));

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章