链表
定义
- 是一组节点的集合
- 每个节点都使用一个对象的引用来指向的后继
- 每个节点的引用叫做链表
和数组的不同
- 数组靠它的位置来指向他的引用
- 链表则靠他们相互之间的关系进行引用
链表的抽象定义
- 元素值
- 指向下一个节点的引用
- 指向上一个节点的引用
双向链表的实现
function Node(element) {
this.element = element;
// 下一节点
this.next = null;
// 上一节点
this.prev = null;
}
function Linklist() {
this.head = new Node("head");
this.insert = insert;
this.remove = remove;
this.find = find;
this.display = display;
this.findPreNode = findPreNode;
}
function find(element) {
var curNode = this.head;
console.log(curNode);
while (curNode.element != element) {
curNode = curNode.next;
}
return curNode;
}
function insert(newEl, oldEl) {
var newNode = new Node(newEl);
var curNode = this.find(oldEl);
newNode.next = curNode.next
newNode.preNode = curNode;
curNode.next = newNode;
}
function display() {
var headNode = this.head;
var resMsg = "";
while (headNode.next != null) {
resMsg += headNode.element + ",";
headNode = headNode.next;
}
return resMsg;
}
function remove(element) {
var curNode = this.find(element);
if (curNode != null) {
curNode.prev.next = curNode.next;
curNode.next.prev = curNode.prev;
curNode.prev = null;
curNode.next = null;
}
}
function findPreNode(element) {
var curNode = this.head;
while (curNode.next != null && curNode.next.element != element) {
curNode = curNode.next;
}
return curNode;
}
function findLast() {
var curNode = this.head;
while (curNode.next != null) {
curNode = curNode.next;
}
return curNode;
}
循环列表,将头节点的
this.head.next=this.head;