一、堆棧
- 堆通常是一個可以被看做一棵樹的數組對象,堆總是滿足下列性質,如下所示:
- 堆中某個節點的值總是不大於或不小於其父節點的值;
- 堆總是一棵完全二叉樹。將根節點最大的堆叫做最大堆或大根堆,根節點最小的堆叫做最小堆或小根堆。常見的堆有二叉堆、斐波那契堆等。
- 堆是在程序運行時,而不是在程序編譯時,申請某個大小的內存空間。即動態分配內存,對其訪問和對一般內存的訪問沒有區別。
- 堆是應用程序在運行的時候請求操作系統分配給自己內存,一般是申請/給予的過程。
- 堆是指程序運行時申請的動態內存,而棧只是指一種使用堆的方法(即先進後出)。
- 棧
(stack)
又名堆棧,一個數據集合,可以理解爲只能在一端進行插入或刪除操作的列表。其限制是僅允許在表的一端進行插入和刪除運算。這一端被稱爲棧頂,相對地,把另一端稱爲棧底。
- 棧就是一個桶,後放進去的先拿出來,它下面本來有的東西要等它出來之後才能出來(先進後出)。
- 棧
(Stack)
是操作系統在建立某個進程時或者線程(在支持多線程的操作系統中是線程)爲這個線程建立的存儲區域,該區域具有FIFO
的特性,在編譯的時候可以指定需要的Stack
的大小。
- 棧的基本操作,如下所示:
- 進棧(壓棧):
push
- 出棧:
pop
- 取棧頂:
gettop
- 對於一個棧,我們需要實現添加、刪除元素、獲取棧頂元素、已經是否爲空,棧的長度、清除元素等幾個基本操作,下面是基本定義,代碼如下所示:
function Stack(){
this.items = [];
}
Stack.prototype = {
constructor:Stack,
push:function(element){
this.items.push(element);
},
pop:function(){
return this.items.pop();
},
peek:function(){
return this.items[this.items.length - 1];
},
isEmpty:function(){
return this.items.length == 0;
},
clear:function(){
this.items = [];
},
size:function(){
return this.items.length;
},
print:function(){
console.log(this.items.toString());
}
}
- 棧的基本操作,代碼如下所示:
var stack = new Stack();
console.log(stack.isEmpty());
stack.push(5);
stack.push(8);
console.log(stack.peek());
stack.push(11);
console.log(stack.size());
console.log(stack.isEmpty());
stack.push(15);
stack.pop();
stack.pop();
console.log(stack.size());
console.log(stack.print());
- 通過棧實現對正整數的二進制轉換,代碼如下所示:
function divideBy2(decNumber){
var decStack = new Stack();
var rem;
var decString = '';
while(decNumber > 0){
rem = decNumber%2;
decStack.push(rem);
decNumber = Math.floor(decNumber/2);
}
while(!decStack.isEmpty()){
decString += decStack.pop().toString();
}
return decString;
}
console.log(divideBy2(10));
二、隊列
- 隊列
(Queue)
是一個數據集合,僅允許在列表的一端進行插入,另一端進行刪除。
- 進行插入的一端稱爲隊尾
(rear)
,插入動作稱爲進隊或入隊。進行刪除的一端稱爲隊頭(front)
,刪除動作稱爲出隊。
- 隊列的性質:先進先出
(First-in, First-out)
。
- 雙向隊列:隊列的兩端都允許進行進隊和出隊操作。
- 隊列是遵循
FIFO(First In First Out
,先進先出,也稱爲先來先服務)原則的一組有序的項。隊列在尾部添加新元素,並從頂部移除元素。最新添加的元素必須排在隊列的末尾。隊列要實現的操作基本和棧一樣,只不過棧是FILO
(先進後出),代碼如下所示:
function Queue(){
this.items = [];
}
Queue.prototype = {
constructor:Queue,
enqueue:function(elements){
this.items.push(elements);
},
dequeue:function(){
return this.items.shift();
},
front:function(){
return this.items[0];
},
isEmpty:function(){
return this.items.length == 0;
},
size:function(){
return this.items.length;
},
clear:function(){
this.items = [];
},
print:function(){
console.log(this.items.toString());
}
}
- 隊列的基本使用,代碼如下所示:
var queue = new Queue();
console.log(queue.isEmpty());
queue.enqueue('huang');
queue.enqueue('cheng');
console.log(queue.print());
console.log(queue.size());
console.log(queue.isEmpty());
queue.enqueue('du');
console.log(queue.dequeue());
console.log(queue.print());
- 優先隊列,元素的添加和移除是基於優先級的。實現一個優先隊列,有兩種選項:設置優先級,然後在正確的位置添加元素;或者用入列操 作添加元素,然後按照優先級移除它們。 我們在這裏實現的優先隊列稱爲最小優先隊列,因爲優先級的值較小的元素被放置在隊列最 前面(
1
代表更高的優先級)。最大優先隊列則與之相反,把優先級的值較大的元素放置在隊列最 前面。
- 優先隊列的定義,使用組合繼承的方式繼承自
Queue
隊列,代碼如下所示:
function PriorityQueue(){
Queue.call(this);
};
PriorityQueue.prototype = new Queue();
PriorityQueue.prototype.constructer = PriorityQueue;
PriorityQueue.prototype.enqueue = function(element,priority){
function QueueElement(tempelement,temppriority){
this.element = tempelement;
this.priority = temppriority;
}
var queueElement = new QueueElement(element,priority);
if(this.isEmpty()){
this.items.push(queueElement);
}else{
var added = false;
for(var i = 0; i < this.items.length;i++){
if(this.items[i].priority > queueElement.priority){
this.items.splice(i,0,queueElement);
added = true;
break;
}
}
if(!added){
this.items.push(queueElement);
}
}
}
PriorityQueue.prototype.print = function(){
var result ='';
for(var i = 0; i < this.items.length;i++){
result += JSON.stringify(this.items[i]);
}
return result;
}
- 優先隊列的基本使用,代碼如下所示:
var priorityQueue = new PriorityQueue();
priorityQueue.enqueue("cheng", 2);
priorityQueue.enqueue("du", 3);
priorityQueue.enqueue("huang", 1);
console.log(priorityQueue.print());
console.log(priorityQueue.size());
console.log(priorityQueue.dequeue());
console.log(priorityQueue.size());
三、鏈表
- 鏈表中每一個元素都是一個對象,每個對象稱爲一個節點,包含有數據域key和指向下一個節點的指針
next
。通過各個節點之間的相互連接,最終串聯成一個鏈表。
- 雙鏈表中每個節點有兩個指針:一個指向後面節點、一個指向前面節點。
- 數組的大小是固定的,從數組的起點或中間插入 或移除項的成本很高,因爲需要移動元素(儘管我們已經學過的
JavaScript
的Array
類方法可以幫 我們做這些事,但背後的情況同樣是這樣)。鏈表存儲有序的元素集合,但不同於數組,鏈表中的元素在內存中並不是連續放置的。每個 元素由一個存儲元素本身的節點和一個指向下一個元素的引用(也稱指針或鏈接)組成。
- 相對於傳統的數組,鏈表的一個好處在於,添加或移除元素的時候不需要移動其他元素。然 而,鏈表需要使用指針,因此實現鏈表時需要額外注意。數組的另一個細節是可以直接訪問任何 位置的任何元素,而要想訪問鏈表中間的一個元素,需要從起點(表頭)開始迭代列表直到找到 所需的元素。
- 鏈表的創建,用動態原型模式來創建一個鏈表,列表最後一個節點的下一個元素始終是
null
,代碼如下所示:
function LinkedList(){
function Node(element){
this.element = element;
this.next = null;
}
this.head = null;
this.length = 0;
if((typeof this.append !== 'function')&&(typeof this.append !== 'string')){
LinkedList.prototype.append = function(element){
var node = new Node(element);
var current;
if(this.head === null){
this.head = node;
}else{
current = this.head;
while(current.next !== null){
current = current.next;
}
current.next = node;
}
this.length++;
};
LinkedList.prototype.insert = function(position,element){
if(position > -1 && position < this.length){
var current = this.head;
var previous;
var index = 0;
var node = new Node(element);
if(position == 0){
node.next = current;
this.head = node;
}else{
while(index++ < position){
previous = current;
current = current.next;
}
node.next = current;
previous.next = node;
}
this.length++;
return true;
}else{
return false;
}
};
LinkedList.prototype.removeAt = function(position){
if(position > -1 && position < this.length){
var current = this.head;
var previous = null;
var index = 0;
if(position == 0){
this.head = current.next;
}else{
while(index++ < position){
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.length--;
return current.element;
}else{
return null;
}
};
LinkedList.prototype.remove = function(element){
var index = this.indexOf(element);
return this.removeAt(index);
};
LinkedList.prototype.indexOf = function(element){
var current = this.head;
var index = 0;
while(current){
if(current.element === element){
return index;
}
index++;
current = current.next;
}
return -1;
};
LinkedList.prototype.isEmpty = function(){
return this.length === 0;
};
LinkedList.prototype.size = function(){
return this.length;
};
LinkedList.prototype.toString = function(){
var string = '';
var current = this.head;
while(current){
string += current.element;
current = current.next;
}
return string;
};
LinkedList.prototype.getHead = function(){
return this.head;
};
}
}
- 鏈表的基本使用,代碼如下所示:
var linkedList = new LinkedList();
console.log(linkedList.isEmpty());
linkedList.append('huang');
linkedList.append('du')
linkedList.insert(1,'cheng');
console.log(linkedList.toString());
console.log(linkedList.indexOf('du'));
console.log(linkedList.size());
console.log(linkedList.removeAt(2));
console.log(linkedList.toString());
- 雙向鏈表和普通鏈表的區別在於,在鏈表中, 一個節點只有鏈向下一個節點的鏈接,而在雙向鏈表中,鏈接是雙向的:一個鏈向下一個元素, 另一個鏈向前一個元素。
- 雙向鏈表和鏈表的區別就是有一個
tail
屬性,所以必須重寫insert、append、removeAt
方法。每個節點對應的Node
也多了一個prev
屬性,代碼如下所示:
function inheritPrototype(subType, superType) {
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
var prototype = object(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
function DoublyLinkedList() {
function Node(element) {
this.element = element;
this.next = null;
this.prev = null;
}
this.tail = null;
LinkedList.call(this);
this.insert = function(position, element) {
if (position > -1 && position <= this.length) {
var node = new Node(element);
var current = this.head;
var previous;
var index = 0;
if (position === 0) {
if (!this.head) {
this.head = node;
this.tail = node;
} else {
node.next = current;
current.prev = node;
this.head = node;
}
} else if (position == this.length) {
current = this.tail;
current.next = node;
node.prev = current;
this.tail = node;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = node;
node.next = current;
current.prev = node;
node.prev = previous;
}
this.length++;
return true;
} else {
return false;
}
};
this.append = function(element) {
var node = new Node(element);
var current;
if (this.head === null) {
this.head = node;
this.tail = node;
} else {
current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = node;
node.prev = current;
this.tail = node;
}
this.length++;
};
this.removeAt = function(position) {
if (position > -1 && position < this.length) {
var current = this.head;
var previous;
var index = 0;
if (position === 0) {
this.head = current.next;
if (this.length === 1) {
this.tail = null;
} else {
this.head.prev = null;
}
} else if (position === (this.length - 1)) {
current = this.tail;
this.tail = current.prev;
this.tail.next = null;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = current.next;
current.next.prev = previous;
}
this.length--;
return current.element;
} else {
return false;
}
};
}
inheritPrototype(DoublyLinkedList, LinkedList);
- 雙向鏈表的基本使用,代碼如下所示:
var doublyList = new DoublyLinkedList();
console.log(doublyList.isEmpty());
doublyList.append('huang');
doublyList.append('du')
doublyList.insert(1, 'cheng');
console.log(doublyList.toString());
console.log(doublyList.indexOf('du'));
console.log(doublyList.size());
console.log(doublyList.removeAt(2));
console.log(doublyList.toString());
- 循環鏈表可以像鏈表一樣只有單向引用,也可以像雙向鏈表一樣有雙向引用。循環鏈表和鏈 表之間唯一的區別在於,最後一個元素指向下一個元素的指針
(tail.next)
不是引用null
, 而是指向第一個元素(head)
。雙向循環鏈表有指向head
元素的tail.next
,和指向tail
元素的head.prev
。