堆疊( Stack ) 與佇列( Queue )

Download Report

Transcript 堆疊( Stack ) 與佇列( Queue )

堆疊與佇列
2009.04 綠園
堆疊(Stack)



將資料依序從資料群下面(buttom)儲存起來,
並視需要從資料群的上面(top)將資料取出的
方式之資料結構,稱為堆疊 。
特性:last in first out (後進先出)。
動作:
create:建立一個空堆疊。
push :將資料存入堆疊。
pop
:將資料從堆疊中取出。
empty :判斷堆疊是否為空堆疊。
full :判斷堆疊是否已滿。
堆疊(Stack)
MaxSize = 7
6
5
4
top
3
D
2
C
1
B
0
A
堆疊(Stack)
MaxSize = 7
push E
6
5
4
top
3
D
2
C
1
B
0
A
堆疊(Stack)
MaxSize = 7
push E
6
5
4
E
3
D
2
C
1
B
0
A
top
堆疊(Stack)
MaxSize = 7
push E
6
top
5
4
E
3
D
2
C
1
B
0
A
堆疊(Stack)
MaxSize = 7
6
pop
5
top
4
E
3
D
2
C
1
B
0
A
堆疊(Stack)
MaxSize = 7
6
pop
5
top
4
E
3
D
2
C
1
B
0
A
堆疊(Stack)
MaxSize = 7
6
pop
5
top
4
3
D
2
C
1
B
0
A
堆疊(Stack)
MaxSize = 7
pop
6
5
top
4
3
D
2
C
1
B
0
A
堆疊(Stack)
MaxSize = 7
6
5
top
4
3
D
2
C
1
B
0
A
#define MaxSize 7
int stack[MaxSize];
int top=0;
【push 的演算法】
int push(int n)
{
if (top<MaxSize)
{
stack[top]=n;
top++;
return 0;
}
else
return -1;
}
/* 堆疊大小 */
/* 全域陣列、堆疊 */
/* 全域變數、堆疊指標 */
【pop 的演算法】
int pop( )
{ int k;
if (top>0)
{
top--;
k=stack[top];
return k;
}
else
return -1;
}
#define MaxSize 7
int stack[MaxSize];
int top=0;
【empty 的演算法】
int empty( )
{
if (top==0)
{
return 1;
}
else
{
return 0;
}
}
/* 堆疊大小 */
/* 全域陣列、堆疊 */
/* 全域變數、堆疊指標 */
【full 的演算法】
int full( )
{
if (top==MaxSize)
{
return 1;
}
else
{
return 0;
}
}
佇列(Queue)



將資料依序從資料群的尾端(tail) 儲存進去,並視
需要從資料群的開頭(head) 將資料取出的方式之資
料結構,稱為佇列。
特性:first in first out(後進先出)
動作:
create :建立一個空佇列。
inqueue :將資料存入佇列中。
dequeue :將資料從佇列中取出。
empty
:判斷佇列是否為空佇列。
front
:傳回佇列前端 head 的值。
佇列(Queue)
MaxSize = 7
0
1
2
3
A
B
C
D
head
4
tail
5
6
佇列(Queue)
MaxSize = 7
0
1
2
3
A
B
C
D
4
5
6
inqueue E
head
tail
佇列(Queue)
MaxSize = 7
0
1
2
3
4
A
B
C
D
E
5
6
inqueue E
head
tail
佇列(Queue)
MaxSize = 7
0
1
2
3
4
A
B
C
D
E
5
6
inqueue E
head
tail
佇列(Queue)
MaxSize = 7
0
1
2
3
4
A
B
C
D
E
5
dequeue
head
tail
6
佇列(Queue)
MaxSize = 7
0
1
2
3
4
A
B
C
D
E
5
dequeue
head
tail
6
佇列(Queue)
0
MaxSize = 7
1
2
3
4
B
C
D
E
5
dequeue
head
tail
6
佇列(Queue)
0
MaxSize = 7
1
2
3
4
B
C
D
E
5
dequeue
head
tail
6
#define MaxSize 10
int queue[MaxSize];
int head=0;
int tail=0;
/*
/*
/*
/*
佇列大小 */
全域陣列、佇列 */
全域變數、指向開頭資料的指標 */
全域變數、指向尾端資料的指標 */
【inqueue 的演算法】
【dequeue 的演算法】
int inqueue(n)
{
if((tail+1)% MaxSize != head)
{
queue[tail] = n;
tail++;
tail = tail % MaxSize;
return 0;
}
else
return -1;
int dequeue(int *n)
{
if (tail != head)
{
*n = queue[head];
head++;
head = head % MaxSize;
return 0;
}
else
return -1;
}
}
作業練習
【練習一】:檔名 stack_xxxx.cpp
試寫一程式,依序 push 5筆資料進入堆疊,
並依序 pop 出來。在螢幕上出現 pop 出
來的資料。


【練習二】:檔名 queue_xxxx.cpp
試寫一程式,依序 inqueue 5筆資料進入
佇列,並依序 dequeue 出來。在螢幕上出
現 dequeue 出來的資料。