今天来说说链表。链表是由一组节点组成的集合。每个节点都使用一个对象的引用指向它的后继,指向另一个节点的引用叫做链。链表一般有一个头节点。
单链表
function Node(element) {
this.element = element;
this.next = null;
}
function List() {
this.head = new Node("head");
this.find = find;
this.insert = insert;
this.remove = remove;
this.display = display;
this.findPrevious = findPrevious;
}
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);
if(current == null)
return console.log("can't find the 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 findPrevious(item) {
var currNode = this.head;
while(currNode.next != null && currNode.next.element != item) {
currNode = currNode.next;
}
return currNode;
}
function display() {
var current = this.head;
while(current.next != null) {
console.log(current.next.element);
current = current.next;
}
}
- find:当结点的element不等时,指针移到结点的后继节点,直到找到相等的元素。如果没找到的话,会返回一个null,因为最后一个结点的next指针就是null。
- insert:这里书上没有判断null这个问题。如果没有找到这个结点,find返回一个null,那么后面的代码就会报错,所以记得加上判断。
- remove:因为单链表没有指向前驱的指针,所以用find是只能找到要删除的结点位置但是不能记录他前一个结点,所以这里要调用findPrevious()。这里我还纠结了一下万一都没有匹配成功的呢。通过画图发现,如果都没有找到匹配的话是返回最后一个结点,而最后一个结点的next为null,不符合remove条件~
双向链表
function LNode(element) { //双向链表结点
this.element = element;
this.next = null;
this.prev = null;
}
function LList() {
this.head = new LNode("head");
this.find = find;
this.insert = insert;
this.remove = remove;
this.display = display;
}
function insert(newElement.item) {
var newNode = new Node(newElement);
var current = this.find(item);
newNode.next = current.next;
current.next.prev = newNode;
newNode.prev = current;
current.next = newNode;
}
function remove(item) {
var current = this.find(item);
if(current.next != null) {
current.prev.next = current.next;
current.next.prev = current.prev;
current.next = null;
current.prev = null;
}
}
function findLast() {
var currNode = this.head;
while(current.next != null) {
current = current.next;
}
return current;
}
function dispReverse() { //反序显示双向链表的元素
var currNode = this.findLast();
while(currNode.prev != null) {
print(currNode.element);
currNode = currNode.prev;
}
}
- 双向链表结点就多了个指向前驱的指针啦。
- 插入删除操作就是多了指针指向问题,双向链表的作用。。。除了反向显示元素,其他的暂时还看不出,不过肯定有他的优点的,通过做题或许就知道什么时候适合双向链表
循环链表
function CList() {
this.head = new Node("head");
this.head.next = this.head;
}
function display() {
var current = this.head;
while(current.next != null && current.next.element != "head") {
print(current.next.element);
current = current.next;
}
}
- 循环链表的话就是最后那个结点的next是指向head,因为是闭环,所以打印链表的时候注意是否到了最后一个结点,不然就永无止境的循环下去了。
- 当然,不止改display方法,其他方法都要改的,不过道理还是一样。