Upload
noman-qadir-leghari
View
225
Download
0
Embed Size (px)
Citation preview
7/31/2019 Sir Kashif Chapter 3
1/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-1
Chapter 3
Lists, Stacks, and Queues
EE 232 Data Structures
Session-05 , Spring-07
7/31/2019 Sir Kashif Chapter 3
2/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-2
Chapter 3: Lists, Stacks, and Queues
3.1 Abstract Data Types (ADT)
3.2 The List ADT
3.3 The Stack ADT
3.4 The Queue ADT
7/31/2019 Sir Kashif Chapter 3
3/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-3
Chapter 3: Lists, Stacks, and Queues
Our goals: we will learn
The concept ofAbstract
Data Types (ADTS)
How to efficiently
perform operations on
lists
The Stack ADT and itsuse in implementing
recursion
The Queue ADT and itsuse in operating systems
and algorithm design
7/31/2019 Sir Kashif Chapter 3
4/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-4
Chapter 3: Lists, Stacks, and Queues
3.1 Abstract Data Types (ADT)
3.2 The List ADT
3.3 The Stack ADT
3.4 The Queue ADT
7/31/2019 Sir Kashif Chapter 3
5/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-5
Abstract Data Types (ADT)
Data type
a set of objects + a set of operations
Example integer
set of whole numbers {, -2, -1, 0, 1, 2, 3,}
operations: +, -, x, /
7/31/2019 Sir Kashif Chapter 3
6/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-6
Abstract Data Types (ADT)
Abstract Data Type
a set of objects and
the set of operations that can be performed on the
objects
Example
the ListADT
A set of the elements that can be integers Operations: PrintList , MakeEmpty , Insert, Delete,
FindKth
7/31/2019 Sir Kashif Chapter 3
7/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-7
Abstract Data Types (ADT)
Why do we call it abstract?
In an ADTs definition, it is not mentioned how to
implement the set of operations
ADTs are not directly usable
They have to be implemented
A given ADT may have more than one
implementation
7/31/2019 Sir Kashif Chapter 3
8/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-8
Chapter 3: Lists, Stacks, and Queues
3.1Abstract Data Types (ADT)
3.2 The List ADT
3.3 The Stack ADT
3.4 The Queue ADT
7/31/2019 Sir Kashif Chapter 3
9/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-9
The List ADT
Objects
A general list is of the form A1, A2,, AN
where the size of the list isN
and a list of size 0 is called an empty list
Ai+1 follows Aifori 1
We dont define the predecessor ofA1 or the
successor ofAN
The position of element Ai is i
7/31/2019 Sir Kashif Chapter 3
10/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-10
The List ADT
Operations
PrintList: prints the list
MakeEmpty: create an empty list
Find: returns the position of an object in a list
list: 34,12, 52, 16, 12
Find(52)3
Insert: insert an object to the list
Insert(X,3)34, 12, 52, X, 16, 12Delete: delete an element from the list
Delete(52)34, 12, X, 16, 12
FindKth: retrieve the element at a certain position
7/31/2019 Sir Kashif Chapter 3
11/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-11
The List ADT
The List ADT can be implemented using an array or a
linked list
Simple array implementation Elements are stored in contiguously
an estimate of the maximum size of the list is
required and this usually requires a high
overestimate, which wastes considerable space
4 -11-262-1-25-3
A1 AN
7/31/2019 Sir Kashif Chapter 3
12/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-12
The List ADT
Running time of the operations
The running time forPrintListand Find?
O(N)
The running time forFindKth ? O(1)
The running time forInsert?
O(N)
The running time forDelete ?
O(N)
are slow operations,
becausewe have tomove other elements
Can we somehow avoid the linear cost of insertion
and deletion?
7/31/2019 Sir Kashif Chapter 3
13/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-13
The List ADT
Linked Lists
consists of a series of structures, which are not
necessarily adjacent in memory
Each structure or node contains the element and apointer(calledNext) to a structure containing its
successor
A1AN
NULL4 -3 -1..
A node in the list
Pointer is a variable that
contains the address where
some other data are stored
Conceptual view
7/31/2019 Sir Kashif Chapter 3
14/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-14
The List ADT
Running time of the operations
PrintList(L) Find(L, key)
FindKth (L,i) takes O(i)
A1 800 A2 712 A5 0A3 992 A4 692
1000 800 712 992 692
Actual view
O(N)
O(N)
O(N)
7/31/2019 Sir Kashif Chapter 3
15/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-15
The List ADT
Insertion into a Linked List
requires obtaining a new cell from the system and
then executing two pointer maneuvers
Running time O(1)
A1 A3
NULL4 -3 -1
5
A3
A4
A2
7/31/2019 Sir Kashif Chapter 3
16/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-16
The List ADT
Deletion from a Linked List
Requires one pointer change
Running time O(1)
NULL
A1 A4
4 -3 -15
A3delete
A2
7/31/2019 Sir Kashif Chapter 3
17/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-17
The List ADT
Array versus Linked Lists
Linked lists are more complex to code and manage
than arrays, but they have some distinct advantages Dynamic
a linked list unlike an array easily grows and
shrinks in size when necessary
Easy and fast insertions and deletions
7/31/2019 Sir Kashif Chapter 3
18/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-18
The List ADT
Programming Details
NULL
header
(An empty list)
NULLA1 A3A2
header
A header or dummy node placed at position 0 is used
in common practice to keep track of an empty list, for
eventual deletion or even to use again
It also allows us to add a node at the beginning of a list
and to delete the first node in a list
7/31/2019 Sir Kashif Chapter 3
19/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-19
The List ADT #ifndef _List_H#define _List_H
struct Node;typedef struct Node* PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
List MakeEmpty( List L );
int IsEmpty( List L );
int IsLast( Position P, List L );Position Find( ElementType X, List L );
void Delete( ElementType X, List L );
Position FindPrevious( ElementType X, List L );
void Insert( ElementType X, List L, Position P );
void DeleteList( List L );
Position Header( List L );Position First( List L );
Position Advance( Position P );
ElementType Retrieve( Position P );
#endif /* _List_H */
struct Node
{
ElementType Element;Position Next;
};
Programming Details
7/31/2019 Sir Kashif Chapter 3
20/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-20
The List ADT
Programming Details
/* Return true if L is empty */
int
IsEmpty( List L )
{
return L->Next == NULL;
}
Running time?
7/31/2019 Sir Kashif Chapter 3
21/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-21
The List ADT
Programming Details
/* Return true if P is the last position in list L */
int
IsLast( Position P, List L )
{
return P->Next == NULL;}
This implementation does
not use the parameter list L
Running time?
7/31/2019 Sir Kashif Chapter 3
22/93
7/31/2019 Sir Kashif Chapter 3
23/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-23
The List ADT
Programming Details
/* If X is not found, then Next field of returned value is NULL */
/* Assumes a header */
PositionFindPrevious( ElementType X, List L )
{
Position P;
/* 1*/ P = L;
/* 2*/ while( P->Next != NULL && P->Next->Element != X )
/* 3*/ P = P->Next;
/* 4*/ return P;
}
Running time?
7/31/2019 Sir Kashif Chapter 3
24/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-24
The List ADT
Programming Details
A consequence of the
free(P) command is
that the address thatP is pointing to is
unchanged, but the
data that reside at
that address are now
undefined
/* Assume use of a header node */
/* Cell pointed to by P->Next is wiped out */
/* Assume that the position is legal */
void
Delete( ElementType X, List L )
{
Position P, TmpCell;
P = FindPrevious( X, L );if( !IsLast( P, L ) )
{
/* X is found; delete it */
TmpCell = P->Next;
/* Bypass deleted cell */
P->Next = TmpCell->Next;
free( TmpCell );
}
}
Running time?
7/31/2019 Sir Kashif Chapter 3
25/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-25
The List ADTProgramming Details
/* Insert (after legal position P) */
/* Header implementation assumed */
void
Insert( ElementType X, List L, Position P ){
Position TmpCell;
/* 1*/ TmpCell = malloc( sizeof( struct Node ) );
/* 2*/ if( TmpCell == NULL )
/* 3*/ FatalError( "Out of space!!!" );/* 4*/ TmpCell->Element = X;
/* 5*/ TmpCell->Next = P->Next;
/* 6*/ P->Next = TmpCell;
}
Running time?
7/31/2019 Sir Kashif Chapter 3
26/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-26
The List ADT
Common errors
The most common erroryou will encounter is thatyour program will crash
with message, such asmemory accessviolation , orsegmentation violation pointer variable
contains a bogus address pointer is not properlyinitialized
e.g. line1 is omitted
/* Incorrect DeleteList algorithm */
void
DeleteList( List L )
{
Position P;
/* 1*/ P = L->Next;
/* Header assumed */
/* 2*/ L->Next = NULL;
/* 3*/ while( P != NULL )
{/* 4*/ free( P );
/* 5*/ P = P->Next;
}
}
incorrect?
7/31/2019 Sir Kashif Chapter 3
27/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-27
The List ADT
The second common error
is that we think that
declaring a pointer to a
structure creates the
structure Use mallocto create a
structure
It takes as an argument
the number of bytes to beallocated and returns a
pointerto the allocated
memory
/* Correct DeleteList algorithm */
void
DeleteList( List L )
{
Position P, Tmp;
/* 1*/ P = L->Next;
/* Header assumed */
/* 2*/ L->Next = NULL;
/* 3*/ while( P != NULL )
{
/* 4*/ Tmp = P->Next;
/* 5*/ free( P );
/* 6*/ P = Tmp;
}
}
7/31/2019 Sir Kashif Chapter 3
28/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-28
The List ADT
Problems with Linked Lists or Singly Linked Lists
finding the successor of an item easy whatabout the predecessor ?
we cant traverse singly linked lists backwards
So, circular linked lists and doubly linked lists
were invented
NULLA1 A3A2
header
7/31/2019 Sir Kashif Chapter 3
29/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-29
The List ADT
Doubly Linked Lists
Each node points to not only its successor but
also to its predecessor
more space is required (for an extra pointer)
cost of insertions and deletions doubles because
now more pointers to fix
Simplifies deletion
NULLA3 A4A2A1NULL
7/31/2019 Sir Kashif Chapter 3
30/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-30
The List ADT
Circularly Linked Lists
previous element next
A2 A4A3A1
A double circularly linked list
7/31/2019 Sir Kashif Chapter 3
31/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-31
The List ADT
Examples
The Polynomial ADT
Lets define an ADT for single-variable polynomials
(with nonnegative exponents)
Example:
Operations: addition, subtraction, multiplication
iN
i
ixAf(x)
0
94572345 xxxx
1 -7 5 -4 0 9
7/31/2019 Sir Kashif Chapter 3
32/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-32
The List ADT
Implementation
If most of the
coefficients of the
polynomial are
nonzero, we can usea simple array to
store them
typedef struct{
int CoeffArray[ MaxDegree + 1 ];
int HighPower;
} *Polynomial;
void
ZeroPolynomial( Polynomial Poly )
{
int i;for( i = 0; i CoeffArray[ i ] = 0;
Poly->HighPower = 0;
}
7/31/2019 Sir Kashif Chapter 3
33/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-33
The List ADT
Implementation
Ignore the time to
initialize the output
polynomials to
zero, then runningtime is proportional
to the product of
the degree of the
two inputpolynomials
void
MultPolynomial( const Polynomial Poly1,
const Polynomial Poly2, Polynomial PolyProd ){
int i, j;
ZeroPolynomial( PolyProd );
PolyProd->HighPower = Poly1->HighPower +
Poly2->HighPower;
if( PolyProd->HighPower > MaxDegree )
Error( "Exceeded array size" );
else
for( i = 0; i HighPower; i++ )for( j = 0; j HighPower; j++ )
PolyProd->CoeffArray[ i + j ] +=
Poly1->CoeffArray[ i ] *
Poly2->CoeffArray[ j ];
}
7/31/2019 Sir Kashif Chapter 3
34/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-34
The List ADT
Singly Linked lists would definitely be a good alternative
to arrays for sparse polynomials
51123)(1510)(
149219902
141000
1
xxxxP
xxxP
10 1000 5 14 1 0P1 NULL
3 1990 1492-2 11 1 5 0P2 NULL
Each node has the coefficient, the
exponent, and the pointer to next
7/31/2019 Sir Kashif Chapter 3
35/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-35
The List ADT
Multi-lists Registration Problem
A university with 40,000 students and 2,500
courses needs to be able to generate two types of
reports Lists the registration of each class
Lists, by student, the classes that each student
is registered for
Array-based Implementation
2D array of 100 million entries
C1
C2
C3
C4
.
.
.
.
S1 S2..
7/31/2019 Sir Kashif Chapter 3
36/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-36
The List ADT
Multi-lists Linked List implementation
C1
C2
CN
S1 SM
7/31/2019 Sir Kashif Chapter 3
37/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-37
The List ADT
Cursor implementation of Linked Lists
Languages , such as FORTRAN and BASIC, do not
support pointers
Two important features of pointer implementation
Data are stored in a node which also contains
pointer to the next node
Using malloc, we obtain a new node from the
memory and usingfree we can release it
In absence of pointers how would we implement
Linked Lists
Have to simulate the above two features
7/31/2019 Sir Kashif Chapter 3
38/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-38
Chapter 3: Lists, Stacks, and Queues
3.1Abstract Data Types (ADT)
3.2 The List ADT
3.3 The Stack ADT
3.4 The Queue ADT
7/31/2019 Sir Kashif Chapter 3
39/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-39
The Stack ADT
Example
pile of plates
1
2
bottom
top
1
2
3
bottom
top
1bottomtop
running time?
7/31/2019 Sir Kashif Chapter 3
40/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-40
The Stack ADT
A stack is a list with the restriction that insertions
and deletions take place at the same end of the list
according to the last-in-first-out (LIFO) principle
This end is called top The other end is called bottom
Where do we use a stack?
Function calls
Multitasking OS
7/31/2019 Sir Kashif Chapter 3
41/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-41
The Stack ADT
Operations
Push
insert an element onto the top of the stack
an input operation
Pop
remove the most recently inserted elementfrom the stack
an output operation
Top
examines the most recently inserted element
an output operation
7/31/2019 Sir Kashif Chapter 3
42/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-42
The Stack ADT
empty stack
topA
top
push an element
top
push another
A
B
top
pop
A
7/31/2019 Sir Kashif Chapter 3
43/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-43
The Stack ADT
Common errors
A Pop orTop on an empty stack is generallyconsidered an error in the stack ADT
Running out of space when performing a Push is
an implementation error and not an ADT error
Stack Implementations
Since stack is a list, therefore any list
implementation could be used to implement astack
Singly Linked lists
Arrays
7/31/2019 Sir Kashif Chapter 3
44/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-44
The Stack ADT
Linked List Implementation of Stacks
Push is performed by inserting at
the front of the list
Pop is performed by deleting theelement at the front of list
Top operation returns the value
of the element at the front
NULL
Top of Stack
7/31/2019 Sir Kashif Chapter 3
45/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-45
The Stack ADT
Programming details
Implementing the
stack with a header
#ifndef _Stack_h#define _Stack_h
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;int IsEmpty( Stack S );
Stack CreateStack( void );
void DisposeStack( Stack S );
void MakeEmpty( Stack S );
void Push( ElementType X, Stack S );
ElementType Top( Stack S );
void Pop( Stack S );
#endif /* _Stack_h */
struct Node
{
ElementType Element;
PtrToNode Next;
};
7/31/2019 Sir Kashif Chapter 3
46/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-46
The Stack ADT
Programming details
int
IsEmpty( Stack S )
{
return S->Next == NULL;
}
Running time?
7/31/2019 Sir Kashif Chapter 3
47/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-47
The Stack ADT
Programming details
Stack
CreateStack( void )
{
Stack S;
S = malloc( sizeof( struct Node ) );
if( S == NULL )
FatalError( "Out of space!!!" );
S->Next = NULL;
MakeEmpty( S );
return S;
}
Running time?
7/31/2019 Sir Kashif Chapter 3
48/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-48
The Stack ADT
Programming details
void
MakeEmpty( Stack S ){
if( S == NULL )
Error( "Must use CreateStack first" );
else
while( !IsEmpty( S ) )
Pop( S );
}
Running time?
7/31/2019 Sir Kashif Chapter 3
49/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-49
The Stack ADTProgramming details
void
Push( ElementType X, Stack S )
{
PtrToNode TmpCell;
TmpCell = malloc( sizeof( struct Node ) );
if( TmpCell == NULL )
FatalError( "Out of space!!!" );
else
{
TmpCell->Element = X;TmpCell->Next = S->Next;
S->Next = TmpCell;
}
}
Running time?
7/31/2019 Sir Kashif Chapter 3
50/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-50
The Stack ADT
Programming details
ElementType
Top( Stack S ){
if( !IsEmpty( S ) )
return S->Next->Element;
Error( "Empty stack" );
return 0; /* Return value used to avoid warning */
}
Running time?
7/31/2019 Sir Kashif Chapter 3
51/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-51
The Stack ADTProgramming details
void
Pop( Stack S )
{
PtrToNode FirstCell;
if( IsEmpty( S ) )
Error( "Empty stack" );
else
{
FirstCell = S->Next;S->Next = S->Next->Next;
free( FirstCell );
}
}
Running time?
7/31/2019 Sir Kashif Chapter 3
52/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-52
The Stack ADT
Linked List Implementation of Stacks
The malloc andfree instructions are expensive as
compared to the pointer manipulations
Linked Lists carefully checks for errors Pop on an empty stack
Push on a full stack
7/31/2019 Sir Kashif Chapter 3
53/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-53
The Stack ADT
Array Implementation of Stacks
Need to declare an array size ahead of time
Generally this is not a problem, because in typical
applications, even if there are a quite a few stack
operations, the actual number of elements in the
stack at any time never gets too large
7/31/2019 Sir Kashif Chapter 3
54/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-54
The Stack ADT
Array Implementation of Stacks With each stack, TopOfStackis defined that stores
the array index of the top of the stack
for an empty stack, TopOfStackis set to -1
Push
Increment TopOfStackby 1
Set Stack[TopOfStack] = X
Pop
Set return value to Stack[TopOfStack]
Decrement TopOfStackby 1
These are performed in very fast constant time
7/31/2019 Sir Kashif Chapter 3
55/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-55
The Stack ADT
On some machines, Pushes and Pops (of integers) canbe written in one machine instruction, operating on aregister with auto-increment and auto-decrementaddressing
TOS = -1
A TOS = 0Stack[TOS]
A
B TOS= 1
Stack[TOS]
7/31/2019 Sir Kashif Chapter 3
56/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-56
The Stack ADT
Programming details #ifndef _Stack_h#define _Stack_h
struct StackRecord;
typedef struct StackRecord *Stack;
int IsEmpty( Stack S );
int IsFull( Stack S );Stack CreateStack( int MaxElements );
void DisposeStack( Stack S );
void MakeEmpty( Stack S );
void Push( ElementType X, Stack S );
ElementType Top( Stack S );void Pop( Stack S );
ElementType TopAndPop( Stack S );
#endif /* _Stack_h */
struct StackRecord
{
int Capacity;
int TopOfStack;
ElementType* Array;};
#define EmptyTOS ( -1 )
#define MinStackSize ( 5 )
7/31/2019 Sir Kashif Chapter 3
57/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-57
The Stack ADTProgramming details
StackCreateStack( int MaxElements )
{
Stack S;
/* 1*/ if( MaxElements < MinStackSize )
/* 2*/ Error( "Stack size is too small" );
/* 3*/ S = malloc( sizeof( struct StackRecord ) );
/* 4*/ if( S == NULL )
/* 5*/ FatalError( "Out of space!!!" );
/* 6*/ S->Array = malloc( sizeof( ElementType ) * MaxElements );
/* 7*/ if( S->Array == NULL )
/* 8*/ FatalError( "Out of space!!!" );/* 9*/ S->Capacity = MaxElements;
/*10*/ MakeEmpty( S );
/*11*/ return S;
}
7/31/2019 Sir Kashif Chapter 3
58/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-58
The Stack ADT
Programming details
void
DisposeStack( Stack S )
{ if( S != NULL )
{
free( S->Array );
free( S );
}
}
7/31/2019 Sir Kashif Chapter 3
59/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-59
The Stack ADT
Programming details
intIsEmpty( Stack S )
{
return S->TopOfStack == EmptyTOS;
}
7/31/2019 Sir Kashif Chapter 3
60/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-60
The Stack ADT
Programming details
voidMakeEmpty( Stack S )
{
S->TopOfStack = EmptyTOS;
}
7/31/2019 Sir Kashif Chapter 3
61/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-61
The Stack ADT
Programming details
void
Push( ElementType X, Stack S )
{
if( IsFull( S ) )
Error( "Full stack" );
else
S->Array[ ++S->TopOfStack ] = X;}
7/31/2019 Sir Kashif Chapter 3
62/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-62
The Stack ADT
Programming details
ElementType
Top( Stack S )
{
if( !IsEmpty( S ) )
return S->Array[ S->TopOfStack ];
Error( "Empty stack" );
return 0; /* Return value used to avoid warning */}
7/31/2019 Sir Kashif Chapter 3
63/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-63
The Stack ADT
Programming details
void
Pop( Stack S )
{
if( IsEmpty( S ) )
Error( "Empty stack" );
else
S->TopOfStack--;}
7/31/2019 Sir Kashif Chapter 3
64/93
7/31/2019 Sir Kashif Chapter 3
65/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-65
The Stack ADT
Applications Balancing Symbols
A problem in elementary algebra is to decide if an
expression containing several kinds of brackets,
such as [,] , {,}, (,), is correctly bracketed This is the case if
There are same number of left and right
brackets of each kind, and
When a right bracket appears, the most recentpreceding unmatched left bracket should be of
the same type
7/31/2019 Sir Kashif Chapter 3
66/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-66
The Stack ADT
Symbol Balancing Algorithm
Scan the expression from left to right
When a left bracket is encountered , push it ontothe stack
When a right bracket is encountered, stack ispopped (if stack is empty, too many right brackets)and brackets are compared
If they are of the same type, scanning continues
Otherwise the expression is incorrectly bracketedAt the end of expression, if the stack is empty, it is
correctly bracketed otherwise, there are too manyleft brackets
7/31/2019 Sir Kashif Chapter 3
67/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-67
The Stack ADT
Postfix Expressions or Reverse Polish Notations
The expression x + y , where the operator is
present in between the operands is called infix
notation
4.99 x1.06 + 5.99 + 6.99 x1.06
The expression x y +, where the operator is
present after the operands is called postfix or
reverse Polish notation 4.99 1.06 x 5.99 + 6.99 1.06 x +
7/31/2019 Sir Kashif Chapter 3
68/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-68
The Stack ADT
Advantages over infix notation
Algebraic formulas can be expressed without
parentheses
Evaluating formulas on computers with stacks is
convenient
Infix operators have precedence which is arbitrary
e.g. left shift has precedence over Boolean
AND? Who knows?
7/31/2019 Sir Kashif Chapter 3
69/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-69
The Stack ADT
A B + C x D + E F
+ G + /
((A + B) x C + D)/
(E + F + G)
A B x C /A x B / C
A B + C D - /(A + B) / (C - D)
A B x C D x +A x B + C x D
A B x C +A x B + C
A B C x +A + B x C
RPNInfix
7/31/2019 Sir Kashif Chapter 3
70/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-70
The Stack ADT
Evaluating the Postfix expression with the Stack
Read in the RPN input
If the input is an operand, push onto the stack
If the input is an operator, pop the top twooperands off stack, perform operation, and
Push the result onto the stack
7/31/2019 Sir Kashif Chapter 3
71/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-71
The Stack ADT
Infix to postfix conversion
Several algorithms for converting the infix formula
into reverse Polish notation exist
The following algorithm uses the stack for the
conversion
Example
a + b * c + (d * e + f) * g -> infix
a b c * + d e * f + g * + -> postfix
7/31/2019 Sir Kashif Chapter 3
72/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-72
The Stack ADT Conversion algorithm
Read the infix expression as input
If input is an operand, output the operand
If input is an operator +, -, *, /, then pop and output
all operators of >= precedence , and pushoperator onto the stack
If input is (, then push it onto the stack
If input is ), then pop and output all operators untilsee a ( on the stack
Pop the ( without output
If no more input then pop and output all operatorson stack
7/31/2019 Sir Kashif Chapter 3
73/93
Th S k ADT
7/31/2019 Sir Kashif Chapter 3
74/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-74
The Stack ADT
Function Calls In almost all programming languages, calling a
function involves the use of a stack
To store the local variables
These can accessed from inside the functionbut cease to be accessible once the function
has returned->an absolute memory address?
To store the return address
Stack frame = local variables + return address
Th St k ADT
7/31/2019 Sir Kashif Chapter 3
75/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-75
The Stack ADT
Function Callsfunc2(int param3, param4) {
int p5, p6;
}
func1(int param1, int param2) {
int p3, p4;
func2(p3, p4);
}
int main() {int p1, p2;
func1(p1, p2);
}
Parameters
Return Address
Locals of main
Parameters
Locals of func1Return Address
Parameters
Locals of func2
Return Addressstack frame
or
activation record
Call Stack
7/31/2019 Sir Kashif Chapter 3
76/93
Th St k ADT
7/31/2019 Sir Kashif Chapter 3
77/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-77
The Stack ADT
This routine whichprints out a linked list, is
perfectly legal and
actually correct
However, if the listconsists of 20,000
elements, what would
happen?
void
PrintList (List L)
{
if( L != NULL)
{
PrintElement( L->Element );
PrintList( L->Next);
}}
May run out of stack space
and the program may crash
7/31/2019 Sir Kashif Chapter 3
78/93
Ch t 3 Li t St k d Q
7/31/2019 Sir Kashif Chapter 3
79/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-79
Chapter 3: Lists, Stacks, and Queues
3.1Abstract Data Types (ADT)
3.2 The List ADT
3.3 The Stack ADT
3.4 The Queue ADT
Th Q ADT
7/31/2019 Sir Kashif Chapter 3
80/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-80
The Queue ADT
A queue is a list with the restriction that insertionstake place at end of the list and deletions take place
at the start of the list according to the first-in-first-out
(FIFO) principle
The end of the list is called rear
The start of the list is known as front
Examples
Keeping track of computing jobs e.g. printing Client-server model
7/31/2019 Sir Kashif Chapter 3
81/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-81
The Queue ADT
Operations
Enqueue
Inserts an element at the end of the list (called
rear)
Dequeue
Deletes (and returns) an element at the start of
the list (known as the front)
Remove
(Dequeue) rearfrontInsert
(Enqueue)
Th Q ADT
7/31/2019 Sir Kashif Chapter 3
82/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-82
The Queue ADT
Implementation of Queue
Since queue is a list, so any list implementation is
legal for a queue
Array implementation
Linked List implementation
Th Q ADT
7/31/2019 Sir Kashif Chapter 3
83/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-83
The Queue ADT
Array Implementation
For each queue data structure, we define
an array Queue[]
the ends of the queue, Front and Rear the number of elements that are actually in the
queue, Size
Th Q ADT
7/31/2019 Sir Kashif Chapter 3
84/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-84
The Queue ADT
To Enqueue an element X
IncrementSizeandRear
SetQueue[Rear] =X
ToDequeuean element Set the return value to Queue[Front]
Decrement Size and increment Front
rearfront
5 2 7 1
Th Q ADT
7/31/2019 Sir Kashif Chapter 3
85/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-85
The Queue ADT
Problem with this implementationAfter 7Enqueues, the queue appears to be full,
since Rear is now 7, and the nextEnqueue would
be in a nonexistent position
there might only be a few elements in thequeue because several elements may have
already been dequeued
rearfront
5 2 7 1
The Q e e ADT
7/31/2019 Sir Kashif Chapter 3
86/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-86
The Queue ADT
rearfront
2 4
rear front
2 41
rear front
2 41 3
rear front
2 41 3
Initial state
AfterEnqueue(1)
AfterEnqueue(3)
AfterDequeue
The Queue ADT
7/31/2019 Sir Kashif Chapter 3
87/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-87
The Queue ADT
AfterDequeue
AfterDequeue
AfterDequeue
rearfront
2 41 3
rearfront
2 41 3
rear front
2 41 3
The Queue ADT
7/31/2019 Sir Kashif Chapter 3
88/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-88
The Queue ADT
Programming Details
#ifndef _Queue_h
#define _Queue_h
struct QueueRecord;
typedef struct QueueRecord *Queue;
int IsEmpty( Queue Q );
int IsFull( Queue Q );Queue CreateQueue( int MaxElements );
void DisposeQueue( Queue Q );
void MakeEmpty( Queue Q );
void Enqueue( ElementType X, Queue Q );
ElementType Front( Queue Q );
void Dequeue( Queue Q );
ElementType FrontAndDequeue( Queue Q );
#endif /* _Queue_h */
struct QueueRecord
{
int Capacity;
int Front;
int Rear;
int Size;
ElementType *Array;};
The Queue ADT
7/31/2019 Sir Kashif Chapter 3
89/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-89
The Queue ADT
Programming Details
int
IsEmpty( Queue Q ){
return Q->Size == 0;
}
The Queue ADT
7/31/2019 Sir Kashif Chapter 3
90/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-90
The Queue ADT...
Programming Details
void
MakeEmpty( Queue Q ){
Q->Size = 0;
Q->Front = 1;
Q->Rear = 0;}
The Queue ADT
7/31/2019 Sir Kashif Chapter 3
91/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-91
The Queue ADT
Programming Details
static int
Succ( int Value, Queue Q ){
if( ++Value == Q->Capacity )
Value = 0;
return Value;
}
The Queue ADT
7/31/2019 Sir Kashif Chapter 3
92/93
Copyright Kashif Javed Lists, Stacks, and Queues 3-92
The Queue ADT
Programming Details
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;
}
}
7/31/2019 Sir Kashif Chapter 3
93/93