/*
- 实现链表类Linklist
- @time:2017-12-28
- @author:谢海涛
- */
/*
- Node类用来表示节点
- */
function Node(element) {
this.element = element;
this.next = null;
}
/*
- LinkList类提供操作方法
- */
function LList() {
this.head = new Node('head');
this.find = find;
this.insert = insert;
this.remove = remove;
this.display = display;
this.findPrevious = findPrevious;
}
/**
- 查找指定的节点
- @param item
- @return 返回包含该数据的节点,否则返回null
*/
function find(item) {
var currNode = this.head;
while (currNode.element != item) {
currNode = currNode.next
}
return currNode;
}
/**
- @param newElement 插入的新节点
- @param item 要找的节点
*/
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;
}
}
/**
- 找到item之前的节点
- @param item
- @returns {HTMLHeadElement|Node}
*/
function findPrevious(item) {
var currNode = this.head;
while ((currNode.next != null) && (currNode.next.element != item)) {
currNode = currNode.next;
}
return currNode;
}
function remove(item) {
var prevNode = this.findPrevious(item);
console.log(prevNode)
if (prevNode.next != null) {
prevNode.next = prevNode.next.next;
}
}
var cities = new LList();
cities.insert('zhanjiang', 'head');
cities.insert('guangzhou', 'zhanjiang');
cities.insert('shenzhen', 'guangzhou');
cities.display();
cities.remove('guangdzhou');
cities.display();