js数据结构之链表

来源:互联网 发布:midi伴奏制作软件 编辑:程序博客网 时间:2024/06/05 18:08
//定义节点function ListNode(val) {    this.val = val;    this.next = null;}//定义链表//链表中有头结点和一些方法function LinkedList() {    this.head = new ListNode('head');    this.find = find;    this.insert = insert;    this.remove = remove;    this.show = show;    this.findFront = findFront;}//定义一些方法//查找节点function find(item) {    var curNode = this.head;    while (curNode.val != item) {        curNode = curNode.next;    }    return curNode; //找到就返回结点数据,没有就返回null}//插入节点function insert(newElement, item) {    //插入的节点,和位置    var newNode = new ListNode(newElement);    var curNode = this.find(item);    var nextNode = curNode.next;    // newNode.next = curNode.next;    curNode.next = newNode;    newNode.next = nextNode;}//找到前节点function findFront(item) {    var curNode = this.head;    if (curNode.next.val != item) {        curNode = curNode.next;    }    return curNode;}//删除节点function remove(item) {    var frontNode = this.findFront(item);    var curNode = this.find(item);    frontNode.next = curNode.next;}//遍历节点function show() {    var curNode = this.head,        result = '';    while (curNode.next != null) {        result += curNode.next.val;        curNode = curNode.next;    }    return result;}

测试

    var list = new LinkedList();    list.insert('a', 'head')    list.insert('b', 'a')    list.insert('c', 'b')    console.log(list.show())    list.remove('a')    console.log(list.show())
原创粉丝点击