数据结构的学习:
关于单链表(JS中):
看了很多关于单链表的帖子云里雾里,加上c++已经还给老师了,自己看书等多方查证终于对于单链表有一个概念,并明白为什么很多帖子关于初始化链表的代码。
定义:每个结点只有一个指针域的链表称为单链表。
结点:在存储数据的时候同时存储一个指针
头指针→头结点[head,next]→结点:[data数据,next指针]
头指针的意义在于访问链表时,总的知道整个链表从哪里开始,从哪里结束。由于链表的Next特性,知道了头结点也就能访问整个链表,所以头指针是必须存在的,如下示例中所有的操作都是先从头结点开始。
我喜欢js,所以用js写:
(js源代码)
//结点类
var Node = function (e){
this.elem = e; //含有一个data元素一个next指针
this.next = null;
}
//链表类
var LinkedList = function(){
this.head = new Node();
this._len = 0;
}
//添加
LinkedList.prototype.toAppend = function(e){
var node = new Node(e);
var n = this.head;
while(n.next !=null){
n = n.next;
}
n.next = node;
this._len++;
}
//查看一下
LinkedList.prototype.toLog = function(){
var n = this.head.next;
var c=0;
while(n != null){
console.log(c++);
console.log('>',n.elem)
n = n.next;
console.log("n:");
console.log(n)
} }
//打印在工作台
var lin = new LinkedList();
lin.toAppend(55);
lin.toAppend(23);
lin.toAppend(22);
lin.toLog();