Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 67

Lecture 3: Stack & Queue

ROAD MAP
Abstract Data Types (ADT)
The List ADT
• Array implementation of lists
• Linked list implementation of lists
• Cursor implementation of lists
• Example
The Stack ADT
• Basic Concepts
• Array implementation of stacks
• Linked list implementation of stacks
• Applications of stacks
• Stacks and recursion implementation
The Queue ADT
• Link list implementation of queues
• Array implementation of queues

2
Stacks
(1) The concept of stacks
(I) Definition of ADT stack
(II) Implementation of stacks
---linked list implementation of stacks;
---Array implementation of stacks.
(2) Applications of stacks
(I) Balancing Symbols (Bracket Matching)
(II) Postfix Expressions
(III) Infix to Postfix Conversion
(3) Stacks and recursion implementation

3
Basic Concepts
Stack Definition: A List with the restriction that insertions
and deletions can be performed only from one end, called
top.
First in, last out( FILO ) lists.
Or last in, first out ( LIFO ) lists.
Take off
Add on

4
Basic Concepts

Top: the end of the list, namely, the operation end.


Bottom : the head of the list.
Push: Insert an element into the end of the list.
Pop: Delete an element from the end of the list.

Pop
Push
an Top
Bottom Top …

a1 a2 a3 ...... an-1 an a3

a2
a1 Bottom
5
Basic Concepts
ADT Stack {
Data Object : D = {ai | ai∈ Elemset, (i=1,2,…,n, n≥0)}
Data relations : R1 = { < ai-1,ai > |ai-1,ai ∈ D,(i=2,3,…,n)} assume
an is top, a1 is bottom.
Basic Operations :
InitStack(&S); DestroyStack(&S)
StackLength(S); StackTravers(S, visit())
Push(&S, e); Pop(&S, &e); GetTop(S, &e) an Top
ClearStack(&S); StackEmpty(s) …
}ADT Stack
a3

a2
a1 Bottom

6
Basic Concepts
InitStack(&S) //Create an empty Stack
DestroyStack(&S) //If S exists, Destroy it
ClearStack(&S) //If S exists, make the Stack empty.
StackEmpty(S) //if S exists, return TRUE,otherwise return
FALSE.
StackLength(S) //return the length of Stack
GetTop(S,&e) // If S exists and non-empty,return the top element
Push(&S,e) // Insert e as the top element
Pop(&S,&e) // If Stack exists and non-empty, set the top element
to e, then delete the top element.
StackTraverse(S,visit()) //visit all of elements in the Stack

7
Basic Concepts
Question1 : The insertion sequence of a stack is
12345 , If it is allowed to pop from the stack in
the process of push , So is it possible that the
order of pop is 43512 or 12345?

Question2 : If the push order is 123456,Is


the pop order 435612 or 135426?
Q3 The push order is 123 , If it is allowed to pop from the
stack in the process of push , What is the possible out of
stack sequence?

① push1pop1 , 2push2pop , 3push3pop , 123 ;


② 1push1pop , 2 、 3push 3 、 2pop , 132 ;
③ 1 、 2push , 2pop , 3push3pop , 1pop 231 ;
④ 1 、 2push , 2 、 1pop , 3push3pop , 213 ;
⑤ 1 、 2 、 3push , 3 、 2 、 1 pop , 321 ;
ROAD MAP
Abstract Data Types (ADT)
The List ADT
• Array implementation of lists
• Linked list implementation of lists
• Cursor implementation of lists
• Example
The Stack ADT
• Basic Concepts
• Array implementation of stacks
• Linked list implementation of stacks
• Applications of stacks
• Stacks and recursion implementation
The Queue ADT
• Link list implementation of queues
• Array implementation of queues

10
Array implementation of stacks

The Pointer for end of list called as top pointer.


//----- Array implementation of stacks-----
#define STACK_INIT_SIZE 100;
#define STACKINCREMENT 10;
typedef struct SqStack {
SElemType *base;
SElemType *top;
int stacksize;
} SqStack;
11
Array implementation of stacks
Full Empty
Array s[M]
top
5 top F 5 5
4 top E 4 4
3 top D 3 3
top 2
2 top C 2 top B 1
1 top B 1
top top A 0
base 0 top A 0 base
base Pop
Null Push
Bottom Pointer When top==base,Stack
base, always empty , If run Pop, then
points to the underflow;
bottom; top
When top==M, Stack full ,
pointer, is on
the top of the If run push, then
12
Array implementation of stacks

Status InitStack (SqStack *S)


{// Create an empty Stack
(*S).base=(SElemType*)malloc(STACK_INIT_SIZE
*sizeof(SElemType));
if (!(*S).base) exit (OVERFLOW); //assignment failed.
(*S).top = (*S).base;
(*S).stacksize = STACK_INIT_SIZE;
return OK;
}

13
Array implementation of stacks
/* Get the top of the stack*/
int gettop (SqStack s, elementype *e)
{
if ( s.top == s.base )   return (o) ;   /* stack is empty */
(*e) = *(s.top-1) ;
return (1) ;
}
5
top 4
D
3
C 2
B 1
A 0
base
Array implementation of stacks
Status Push (SqStack *S, SElemType e)
{
if ((*S).top - (*S).base >= (*S).stacksize)
{//Stack Full , Extend space
(*S).base = (SElemType *) realloc ( (*S).base,
((*S).stacksize + STACKINCREMENT) *sizeof (SElemType));
if (!(*S).base) exit (OVERFLOW); //Assignment failed.
(*S).top = (*S).base +(*S).stacksize;
(*S).stacksize += STACKINCREMENT;
}
*(*S).top++ = e;
return OK;
}

15
Array implementation of stacks

Status Pop (SqStack *S, SElemType *e) {


// If Stack is Non-empty , let top element to e , then delete

//the top element, return true, otherwise return Error.


if ((*S).top ==(*S).base) return ERROR;
e = *--(*S).top;
return OK;
}

16
ROAD MAP
Abstract Data Types (ADT)
The List ADT
• Array implementation of lists
• Linked list implementation of lists
• Cursor implementation of lists
• Example
The Stack ADT
• Basic Concepts
• Array implementation of stacks
• Linked list implementation of stacks
• Applications of stacks
• Stacks and recursion implementation
The Queue ADT
• Link list implementation of queues
• Array implementation of queues

17
Linked List implementation of stacks

The Pointer of top is the pointer


of head pointer of List
Pointer of top
an an-1 a1 ∧

Note: The pointer


direction of Linked List
Stack

18
Linked List implementation of stacks
 Push Operation
top top
Bottom
p x …... ^

p->next=top ; top=p
 Pop Operation

q top
Bottom
top …... ^

q=top ; top=top->next
19
Linked List implementation of stacks
typedef struct lnode
{
elementype data ;
struct lnode *next ;
} lnode, *linkstack ;

20
Linked List implementation of stacks

int IsEmpty(Stack S);


Stack CreatStack(void);
void DisposeStack(Stack &S);
void MakeEmpty(Stack &S);
void Push(ElementType X, Stack &S);
void Pop(Stack S);
ElementType Top(Stack S);

21
Linked List implementation of stacks

Test for an empty stack

int Isempty(Stack S)
{
return (SNext == NULL);
}

S Header

22
Linked List implementation of stacks

Create an empty stack


stack CreatStack(void)
{ Stack S;
S=malloc(sizeof(struct Node));
if (S==NULL)
printf(“Out of space!!!”);
S->Next = NULL;
return(S);
}
S Header

23
Linked List implementation of stacks
Push onto a stack
void Push(ElementType X, Stack *S)
{ lnode *TmpCell;
TmpCell = malloc(sizeof(struct lnode));
if (TmpCell == NULL)
printf(“failed”);
else
{ TmpCell data = X;
TmpCell Next = (*S) Next;
(*S) Next = TmpCell;
}
} X TmpCell
*S Header
An A2 A1 24
Linked List implementation of stacks
Pop from a stack
void Pop(Stack *S)
{ lnode* FirstCell;
if (ISEmpty(*S)
Error (“Empty stack”);
else
{ FirstCell = (*S) Next;
(*S) Next =(*S) Next Next;
free(FirstCell);
}
}

*S FirstCell
Header
An An-1 A1
25
Linked List implementation of stacks
Return top element in a stack

ElementType Top(Stack S)
{ if (!IsEmpty(S))
return (S Next data);
Error(“Empty stack”);
return 0;
}

26
Linked List implementation of stacks
Make a stack empty:
void MakeEmpty(Stack S)
{ if (S==NULL)
printf(“Error message!”);
else
while (!IsEmpty(S))
pop(S);
}

S
Header
An An-1 A1

27
Linked List implementation of stacks

Summary
(1) The top of the stack pointed by the
header;
(2) The storage space for the changed
node should be managed yourself.

28
Applications ( Conversion )

For Example (1348)10=(2504)8 ,

N N div 8 N mod 8
Calculating

Output
1348 168 4
168 21 0
21 2 5
2 0 2 top
top 2
top 5
top 0 5
0 0
top 4 4 4 4
29
Applications ( Conversion )
void conversion( ) {
initstack(S);
scanf (“%d”,N);
while(N){
push(S , N%8);
N=N/8;
}
while(! Stackempty(s)){
pop(S,e);
printf(“%d”,e);
}
}//conversion

30
Applications
Balancing Symbols

check whether each [ or ( has a correcponding ) or ]


[()] √
[(]) X
[([ ] [ ] ) ] √
[ ( ( )) X
(( )) ] X
[ ( ]) X

31
Applications
Balancing Symbols Algorithm
Create a stack
Read the charecters one by one
If the charecter is ‘(‘ or ‘[‘ push into stack
If the charecter is ‘)’ or ‘]’ pop the stack
if the stack is empty ERROR
if the symbol popped does not match with
character ERROR
Continue until the end of file
At the end of file
if the stack is not empty ERROR
else SUCCESS
32
Applications
PostFix Expressions
5+4*2 infix (中缀) expressions
(5+4)*2 paranthesis are necessary

What if you have a simple calculator ?


5 4 + 2 * = (5+4)*2
5 4 2 * + = 5+(4*2)

How to evaluate postfix expressions ?


• use a stack
• a number  push onto stack
• an operator  pop two values from stack
apply operation
push the result onto stack

33
Applications
PostFix Expressions Top of Stack 5
6
Example :
6 5 + 8 *
Top of Stack
11

Top of Stack 8
11

Top of Stack
88

34
Applications

Conversion

PostFix Expressions

How to obtain a postfix expression?


How to convert infix to postfix?

35
Applications:Function Calls
Function Calls

When a function is called


• Local variables and status should be saved
When the function returns
• Saved values needs to be restored
In what order?

36
Applications:Function Calls
void main() {
f();
}

void f() {
g();
h();
}
void g() {}
void h() {}

37
Applications:Function Calls

(1 (2
) )

top f()
top main() main()

(3 (4
) )
top g() top h()
f() f()
main() main()
38
Applications: Stacks and Recursion
 Definition: Recursion simply means a
function that calls itself directly or
indirectly.
 Recursion should be used freely in the
initial design of algorithms.It is especially
appropriate where the main step toward
solution consists of reducing a problem to
one or more smaller cases.

39
Applications: recursive call
Example: Linked List

Find the last element of a list


void Find ( LinkList L ) {
if ( L→next == NULL )
printf ( L→data);
else Find ( L→next );
}

40
Definition is recursive
 Informal definition: The factorial function of a positive
integer is n! = n(n-1)…1

 Formal definition:

 1, Whenn0
n!  
 Algorithm: n  (n  1)!, When n  1
( 1 ) long int fact(int n) /* n 是非负整数 */
( 2 ) { long f;
(3) if (n==0 ||n==1)
(4) f=1;
(5) else
(6) f=n*fact(n-1); /* 递归调用函数 fact */
( 7 ) return(f);
41
}
n
1
n
2 f=n*fact(1);
main n
f=n*fact(1);
3
f=n*fact(2);
n=3; return 1
f= return 2
(1)fact(n)
return 6

finish

to top
top
top p ( 3 ) w=1(7) 1
top
to ((7)
2 )2
w=2 ( 2 ) w=2
(7) 2
p (11)) 3
( w=3 ((1)
1 )3
w=3 ( 1 ) w=3
(1) 3
Solution method is recursive
Example: Tower of Hanoi

43
 Every recursive process consists of two
parts:
 A smallest, base case that is processed
without recursion; (termination condition)
 A general method that reduces a particular
case to one or more of the smaller cases,

44
The general form of a recursive algorithm
void p (parameters)
if ( stopping condition)
base case that is processed without recursion
else p (smaller parameters); //recursive case

45
Designing Recursive Algorithms
 Find the key step. Begin by asking yourself,“How can
this problem be divided into parts?”or “How will the key
step in the middle be done?”
 Find a stopping rule. This stopping rule is usually the
small, special case that is trivial or easy to handle
without recursion.
 Outline your algorithm. Combine the stopping rule and
the key step, using an if statement to select between
them.
 Check termination. Verify that the recursion will always
terminate. Be sure that your algorithm correctly handles
extreme cases.

46
ROAD MAP
Abstract Data Types (ADT)
The List ADT
• Array implementation of lists
• Linked list implementation of lists
• Cursor imlementation of lists
The Stack ADT
• Linked list implementation of stacks
• Array implementation of stacks
The Queue ADT
• Array implementation of queues
• Linked List implementation of queues

47
THE QUEUE ADT
A queue is a list
insertions at one end
deletions at other end
FIFO (First In First Out)

Operations ?

48
THE QUEUE ADT
Operations
Enqueue
• insert an element
at the end of the
list (rear) dequeue enqueue
Dequeue Queue
• delete the element
at the start of the
list (front)
IsEmpty
• check whether the
queue has an
element or not
49
Implementation of Queue ADT
Linked list implementation of queues
Which end of the linked list is the front?
Which end of the linked list is the back?
How to access both fast?

Array implementation of queues


Where is the back and the front?
When is the queue full?

50
Implementation of Queue ADT
Linked list implementation of queues
keep two pointers the front and the back
• Front is the head of the linked list
• Back is the tail of the linked list

Array implementation of queues


keep positions of the front and the rear. When one
reaches to the end of the Array, it starts over
from the beginning
• Array is used as a circular array
keep track of the size of queue

51
Implementation of Queue ADT
typedef struct QNode{
data *next
QElemType data;
struct QNode *next;
}Qnode, *QueuePtr;

typedef struct {
QueuePtr front; // font pointer
QueuePtr rear; // rear pointer
}LinkQueue;

a1 a2 a3 ...... an-1 an
Rear Pointer
Front Pointer 52
Implementation of Queue ADT
Initialization of a queue
Status InitQueue(LinkQueue &Q)
{ Q.rear=(QueuePtr)malloc(sizeof(QNode) );
Q.front = Q.rear;
if(!Q.front) return(OVERFLOW);
Q.front -> next = NULL; data *next
return OK;
} // InitQueue
header
front
rear
53
Implementation of Queue ADT
Status
DestroyQueue(LinkQueue &Q)
{ while(Q.front ){
Q.rear = Q.front -> next;
free(Q.front); header

Q.front = Q.rear; front


} rear
return OK;
} // DestroyQueue

front X Y
rear
54
Implementation of Queue ADT
Status EnQueue(LinkQueue &Q, QelemType e)
{ p = ( QueuePtr )malloc(sizeof(QNode));
if(!p) return(OVERFLOW);
p->data = e;
p -> next = NULL;
Q.rear ->next = p;
front e
Q.rear = p;
rear
return OK;
} // EnQueue

front X e
rear
p
55
Implementation of Queue ADT
Status DeQueue(LinkQueue &Q, QelemType &e)
{ if(Q.front == Q.rear) retrun ERROR;
p = Q.front -> next;
e = p->data;
Q.front->next = p->next;
if(Q.rear == p) Q.rear = Q.front ;
free(p);
front e
return OK;
rear
} // DeQueue p

front X Y
rear
p
56
Array implementation of queues

struct QueueRecord
{
int Capacity;
int Front, Rear, Size;
ElementType *Array;
Queue
};
size typedef struct QueueRecord *Queue;
Capacity
front

rear

Array a1 a2 …. an

57
Array implementation of queues

Problem: May run out of rooms


(1) Keep front always at 1 by shifting
the contents up the queue, but the
computer solution is inefficient
(2) Use a circular queue (wrap
around) rear rear rearrear rear

A
H B C D E F G

front front front front 58


Array implementation of queues

Problem:How to check the queue is empty?

Size=0
Size=1
Rear=-1
Rear=0

Front=0 59
Array implementation of queues

Problem: How to check if the queue is empty?


(1): When the queue is empty, How do we judge it?
Solution: keep track of size; Size = 5
rear rear rear
Size = 6

Size = 7

H I A B E F G

front
60
front
Empty : front==rear rear
Full : front==rear
4 5 0
3
2 1
rear
J6
J5 4 5 0
e qu eu e
J 5 , J 6 D J6
3
2 1 J4,
J4 J7,J8 J5 5 J7
front , J9En 4 0
queu
e J4 3 2 1 J8
Current front J9
Solution : rear
1.With a sign to record the queue empty or full
2.Only use maxsize-1 units :
Empty : front==rear Full :
(rear+1)%M==front
3.With a size variable, to record the element number 61
Array implementation of queues
struct QueueRecord
{
int Capacity;
int Front; Rear;
int Size;
ElementType*Array ;
} ;
typedef struct QueueRecord *Queue;
static int Succ( int Value, Queue Q)
{
if (++Value == Q Capacity) Value = 0;
return Value;}
62
Array implementation of queues
void Enqueue (ElementType X, Queue Q )
{
if (IsFull(Q) )
Error(‘Full queue’);
else
{
Q Size++;
Q Rear = Succ(Q Rear, Q);
Q Array[Q Rear] = x;
}
}

63
Array implementation of queues

void Dequeue( Queue Q )


{
if( IsEmpty( Q ) )
Error( "Empty queue" );
else
{
Q->Size--;
Q->Front = Succ( Q->Front, Q );
}
}

64
Applications of queues

Print jobs
Computer networks
OS
Real-life waiting lines

65
Array Implementation of Queues

Enqueue Increment queueSize


Increment back
Queue [back] = X
Dequeue  Decrement queueSize
Increment front
return Queue[front-1]

66
Big Summary

( 1 ) ADT
( 2 ) ADT of Lists, Stacks and Queues;
( 3 ) ADT implementation using linked list and
array;
( 3 ) Recursion

67

You might also like