Professional Documents
Culture Documents
Lecture4 Stack&Queue
Lecture4 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
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?
10
Array implementation of stacks
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
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
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
21
Linked List implementation of stacks
int Isempty(Stack S)
{
return (SNext == NULL);
}
S Header
22
Linked List implementation of stacks
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 )
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
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
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
35
Applications:Function Calls
Function Calls
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
40
Definition is recursive
Informal definition: The factorial function of a positive
integer is n! = n(n-1)…1
Formal definition:
1, Whenn0
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?
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
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
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
A
H B C D E F G
Size=0
Size=1
Rear=-1
Rear=0
Front=0 59
Array implementation of queues
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
64
Applications of queues
Print jobs
Computer networks
OS
Real-life waiting lines
65
Array Implementation of Queues
66
Big Summary
( 1 ) ADT
( 2 ) ADT of Lists, Stacks and Queues;
( 3 ) ADT implementation using linked list and
array;
( 3 ) Recursion
67