Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
DS Lecture 06 Stack
3/9/2014
Stack
push A stack is open at one end (the top) only. You can push entry onto the top, or pop the top entry out of the stack. Note that you cannot add/extract entry in the middle of the stack.
pop
top
C B
A
bottom
B
A A
C B A
The last one pushed in is the first one popped out! (LIFO)
B A
When we push entries onto the stack and then pop them out one by one, we will get the entries in reverse order.
4
Stack Operations
Push(X) insert X as the top element of the stack Pop() remove the top element of the stack and return it. Top() return the top element without removing it from the stack.
Stack Operations
top
top top top top 2 push(2) 5 2 push(5) 7 5 2 1 7 5 2 push(1)
push(7)
5
2 7 pop() top 5 2 pop()
2
pop()
top
1 7 5 2
1
top = 3
Array implementation
? ? ? ? B A
stack
#define stack_size 6;
top = 2
stack
8
Initialization of Stack
stack_initialize() { top = -1; }
top
? ? ? ? ? ? entry top = 0
Push()
void push(char i) { if(top==stack_size - 1) cout<<"stack is full; else { top++; stack[top] = i; } }
top
? ? ? ? ? A entry
top= 0 1
10
Pop()
void pop() { if(top<0) cout<<"underflow: stack is empty;
else
{ x = stack[top]; top--; return x; } }
top
? ? ? ? ? ? entry
top= 10
11
Traversing a stack
void show() { int i; for(i=0;i<=top;i++) cout<< stack << i << = <<stack[i]; }
? ? D C B A
stack
top
3 2 1 0
12
Other operations
int top() { return stack[top]; } int IsEmpty() { return ( top == -1 ); } int IsFull() { return ( top == stack_size-1); }
13
stack[0]=7 and top = 0 stack[1]=8 and top = 1 stack[2]=9 and top = 2 x = 9 and top = 1 stack[2]=5 and top = 2 x = 5 and top = 1 x = 8 and top = 0
top
stack
3/9/2014
14
We can avoid the size limitation of a stack implemented with an array by using a linked list to hold the stack elements.
head top 1 7 5 2 1 7 5 2
7 5 2
newNode
push(9)