1、队列
var Queue = function(){
var items = [];
this.enqueue = function(element){
items.push(element);
}
this.dequeue = function(){
return items.shift();
}
this.front = function(){
return items[0];
}
this.isEmpty = function(){
return items.length==0;
}
this.size = function(){
return items.length;
}
}
2、栈
var Stack = function() {
var items = [];
this.push = function(element) {
items.push(element)
}
this.getItems = function() {
return items;
}
this.peek = function() {
return items[items.length - 1];
}
this.pop = function() {
return items.pop();
}
this.isEmpty = function() {
return items.length == 0
}
this.clear = function() {
items = [];
}
this.size = function() {
return items.length;
}
}
3、链表
var linkSheet = function() {
var head = null;
var length = 0;
var Node = function(element) {
this.element = element;
this.next = null;
}
this.append = function(element) {
var node = new Node(element)
if (head == null) {
head = node;
} else {
var current = head;
while (current.next) {
current = current.next;
}
current.next = Node;
}
length++;
}
this.insert = function(position, element) {
if (position >= -1 && position < length) {
var node = new Node(element);
if (position == 0) {
var current = head;
head = node;
head.next = current;
} else {
var index = 0;
var current = head;
var previous = null;
while (index < position) {
previous = current;
current = current.next;
index++;
}
previous.next = node;
node.next = current;
}
length++;
}
}
this.removeAt = function(position){
if(position>-1&&position<length){
if(position==0){
var current = head;
head = current.next;
}
else{
var current = head;
var previous = null;
var index = 0;
while(index<position){
previous = current;
current = current.next;
index++;
}
previous.next= current.next;
}
length--;
return current;
}
return null;
}
this.indexOf = function(element){
var current = head;
var index = 0;
while(current){
if(current.element==element){
return index;
}
current= current.next;
index++;
return index;
}
return -1;
}
this.remove = function(element){
return this.removeAt(this.indexOf(element));
}
this.isEmpty = function(){
return length==0;
}
this.size = function(){
return length;
}
this.getHead = function(){
return head;
}
}