链表存储有序的元素集合,但不同于数组,链表中的元素在内存中并不是连续放置的。每个元素由一个存储元素本身的节点和一个指向下一个元素的引用(指针或链接)组成。
链表的一个好处在于,添加或者移除元素的时候不需要移动其他的元素。然而链表需要使用指针。数组可以直接访问任何位置的元素,而链表想要访问中间的一个元素,需要从起点(表头)开始迭代,直到找到所需的元素。
function LinkList(){
let Node = function(ele){
this.ele = ele;
this.next = null;
}
let length = 0;
let head = null;
// 向链表尾部追加元素
this.append = function(ele){
let node = new Node(ele);
let current;
if(head == null){
head = node;
}else{
current = head;
while(current.next){
current = current.next;
}
current.next = node;
}
length++;
}
// 从链表中移出元素(从特定位置移出)
this.removeAt = function(pos){
// 检查越界值
if(pos >-1 && pos< length){
let current = head,
pre,
index = 0;
if(pos === 0){
head = current.next;
}else{
while(index++ < pos){
pre = current;
current = current.next;
}
pre.next = current.next;
}
length--;
return current.ele;
}else{
return null;
}
}
// 在任意位置插入元素
this.insert = function(pos, ele){
if(pos >= 0 && pos <= length){
let node = new Node(ele),
current = head,
pre,
index = 0;
if(pos == 0){
node.next = current;
head = node;
}else{
while(index++ < pos){
pre = current;
current = current.next;
}
node.next = current;
pre.next = node;
}
length++;
return true;
}else{
return false;
}
}
// 将LinkList对象转换成一个字符串
this.toString = function(){
let current = head,
string = '';
while(current){
string += current.ele;
current = current.next;
}
console.log(string);
return string;
}
// 该方法接收一个值,如果在列表中能找到它,就返回元素的位置,否则返回-1
this.indexOf = function(ele){
let current = head,
index = 0;
while(current){
if(current.ele == ele){
return index;
}
index++;
current = current.next;
}
return -1;
}
// 从链表中移出元素(通过特定的元素)
this.remove = function(ele){
let index = this.indexOf(ele);
return this.removeAt(index);
}
this.isEmpty = function(){
if(length == 0){
console.log('空')
}else{
console.log('不为空')
}
return length == 0;
}
this.size = function(){
console.log(length)
return length;
}
this.getHead = function(){
console.log(head);
return head;
}
}
测试:
var link = new LinkList();
link.append(1);
link.append(2);
link.append(3);
link.append(4);
link.append(5);
link.append(6);
link.toString();
link.removeAt(2);
link.toString();
link.remove(4);
link.toString();
link.isEmpty();
link.size();
link.getHead();
测试结果: