关闭

6、单向链表

标签: 链表
158人阅读 评论(0) 收藏 举报
分类:
var log = console.log;

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

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

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

function findPrevious(item){
    var currNode = this.head;
    while((currNode.next != null) && (currNode.next.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 remove(item){
    var prevNode = this.findPrevious(item);
    if(prevNode.next != null){
        prevNode.next = prevNode.next.next;
    }
}

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

var words = new LList();
words.insert("Late", "head");
words.insert("in", "Late");
words.insert("autumn", "in");
words.insert("winner", "autumn");
words.display();
words.remove("autumn");
words.display();


1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:24425次
    • 积分:960
    • 等级:
    • 排名:千里之外
    • 原创:64篇
    • 转载:12篇
    • 译文:0篇
    • 评论:1条
    最新评论