链表
//定义单向链表的节点类
class Node{
constructor(data){
this.data = data //节点的数据域(数据成员)
this.next = null //节点的指针域(指针成员)
}
}
//定义单向链表类
class SingleLinked{
constructor(){
this.size = 0 //用记录链表中的节点个数
this.head = new Node('head') //是链表的头指针:记录链表的起始地址
this.currentNode = '' //用来记录当前节点
}
//获取链表的长度
getLength(){
return this.size
}
//判断链表是否为空
isEmpty(){
return this.size === 0
}
//遍历链表:不重复访问链表中的每个节点
displayList(){
var list = ''
var currentNode = this.head //指向链表的头指针
while(currentNode){
//若当前节点不为空
list += currentNode.data
currentNode = currentNode.next //让指针指向当前节点的下一个节点
if(currentNode){
list += '->'
}
}
console.log(list)
}
//获取链表的最后一个节点
findLast(){
var currNode = this.head
while(currNode.next){
currNode = currNode.next
}
return currNode;
}
//采用尾插法给链表插入元素
appendNode(element){
var currNode = this.findLast() //找到链表的最后一个节点
var newNode = new Node(element) //创建一个新的节点
currNode.next = newNode
newNode.next = null
this.size++ //链表的长度加1
}
}
栈
栈的基本运算:后进先出,在一端进行插入和删除的数据结构
- 入栈:添加元素
- 出栈:删除元素
- 读栈顶元素
/**
* 栈的构造函数
*/
function Stack() {
/**
* 用数组来模拟栈
* @type {Array}
*/
var items = [];
/**
* 将元素送入栈,放置于数组的最后一位
* @param {Any} element 接受的元素,不限制类型
*/
this.push = function(element) {
items.push(element);
};
/**
* 弹出栈顶元素
* @return {Any} 返回被弹出的值
*/
this.pop = function() {
return items.pop();
};
/**
* 查看栈顶元素
* @return {Any} 返回栈顶元素
*/
this.peek = function() {
return items[items.length - 1];
}
/**
* 确定栈是否为空
* @return {Boolean} 若栈为