SlideShare a Scribd company logo
1 of 93
Lists, Stacks, and Queues
Lists, Stacks, and Queues
1 Abstract Data Types (ADT)
2 The List ADT
3 The Stack ADT
4 The Queue ADT
Lists, Stacks, and Queues
Our goals: we will learn
 The concept of Abstract
Data Types (ADTS)
 How to efficiently
perform operations on
lists
 The Stack ADT and its
use in implementing
recursion
 The Queue ADT and its
use in operating systems
and algorithm design
Lists, Stacks, and Queues
1 Abstract Data Types (ADT)
2 The List ADT
3 The Stack ADT
4 The Queue ADT
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, /
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 List ADT
• A set of the elements that can be integers
• Operations: PrintList , MakeEmpty , Insert, Delete,
FindKth
Abstract Data Types (ADT)…
Why do we call it abstract?
 In an ADT’s 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
Lists, Stacks, and Queues
1 Abstract Data Types (ADT)
2 The List ADT
3 The Stack ADT
4 The Queue ADT
The List ADT
Objects
 A general list is of the form A1, A2,…, AN
• where the size of the list is N
• and a list of size 0 is called an empty list
• Ai+1 follows Ai for i < N and
• Ai-1 precedesAi for i >1
• We don’t define the predecessor of A1 or the
successor of AN
• The position of element Ai is i
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, 12
 Delete: delete an element from the list
• Delete(52)  34, 12, X, 16, 12
 FindKth: retrieve the element at a certain position
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 -1
1
-2
6
2
-1
-2
5
-3
A1
AN
The List ADT…
Running time of the operations
 The running time for PrintList and Find ?
• O(N)
 The running time for FindKth ?
• O(1)
 The running time for Insert ?
• O(N)
 The running time for Delete ?
• O(N)
are slow operations,
because we have to
move other elements
Can we somehow avoid the linear cost of insertion
and deletion?
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 a
pointer (called Next ) to a structure containing its
successor
A1
AN
NULL
4 -3 -1
……..
A node in the list
Pointer is a variable that
contains the address where
some other data are stored
Conceptual view
The List ADT…
Running time of the operations
 PrintList (L)
 Find(L, key)
 FindKth (L,i) takes O(i)
A1 800 A2 712 A5 0
A3 992 A4 692
1000 800 712 992 692
Actual view
O(N)
O(N)
O(N)
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
NULL
4 -3 -1
5
A3
A4
A2
The List ADT…
Deletion from a Linked List
 Requires one pointer change
 Running time O(1)
NULL
A1 A
4
4 -3 -1
5
A3
delete
A2
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
The List ADT…
Programming Details
NULL
header
(An empty list)
NULL
A1 A3
A2
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
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…
The List ADT…
Programming Details…
/* Return true if L is empty */
int
IsEmpty( List L )
{
return L->Next == NULL;
}
Running time?
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?
The List ADT…
Programming Details…
/* Return Position of X in L; NULL if not found */
Position
Find( ElementType X, List L )
{
Position P;
/* 1*/ P = L->Next;
/* 2*/ while( P != NULL && P->Element != X )
/* 3*/ P = P->Next;
/* 4*/ return P;
}
Running time?
3-23
The List ADT…
Programming Details…
/* If X is not found, then Next field of returned value is NULL */
/* Assumes a header */
Position
FindPrevious( 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?
Lists, Stacks, and Queues 3-24
The List ADT…
Programming Details…
 A consequence of the
free(P) command is
that the address that
P 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?
Lists, Stacks, and Queues 3-25
The List ADT…
Programming 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?
Lists, Stacks, and Queues 3-26
The List ADT…
Common errors
 The most common error
you will encounter is that
your program will crash
with message, such as
“memory access
violation” , or
“segmentation violation”
 pointer variable
contains a bogus address
 pointer is not properly
initialized
 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?
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 malloc to create a
structure
 It takes as an argument
the number of bytes to be
allocated and returns a
pointer to 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;
}
}
Lists, Stacks, and Queues 3-28
The List ADT…
Problems with Linked Lists or Singly Linked Lists
 finding the successor of an item easy what
about the predecessor ?
 we can’t traverse singly linked lists backwards
 So, circular linked lists and doubly linked lists
were invented
NULL
A1 A3
A2
header
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
NULL
A3 A4
A2
A1
NULL
Lists, Stacks, and Queues 3-30
The List ADT…
Circularly Linked Lists
previous element next
A2 A4
A3
A1
A double circularly linked list
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
i
N
i
i x
A
f(x) 


0
9
4
5
7 2
3
4
5



 x
x
x
x
1 -7 5 -4 0 9
Lists, Stacks, and Queues 3-32
The List ADT…
Implementation
 If most of the
coefficients of the
polynomial are
nonzero, we can use
a simple array to
store them
typedef struct
{
int CoeffArray[ MaxDegree + 1 ];
int HighPower;
} *Polynomial;
void
ZeroPolynomial( Polynomial Poly )
{
int i;
for( i = 0; i <= MaxDegree; i++ )
Poly->CoeffArray[ i ] = 0;
Poly->HighPower = 0;
}
Lists, Stacks, and Queues 3-33
The List ADT…
Implementation
 Ignore the time to
initialize the output
polynomials to
zero, then running
time is proportional
to the product of
the degree of the
two input
polynomials
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 <= Poly1->HighPower; i++ )
for( j = 0; j <= Poly2->HighPower; j++ )
PolyProd->CoeffArray[ i + j ] +=
Poly1->CoeffArray[ i ] *
Poly2->CoeffArray[ j ];
}
Lists, Stacks, and Queues 3-34
The List ADT…
 Singly Linked lists would definitely be a good alternative
to arrays for sparse polynomials
5
11
2
3
)
(
1
5
10
)
(
1492
1990
2
14
1000
1







x
x
x
x
P
x
x
x
P
10 1000 5 14 1 0
P1 NULL
3 1990 1492
-2 11 1 5 0
P2 NULL
Each node has the coefficient, the
exponent, and the pointer to next
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……………………………..
Lists, Stacks, and Queues 3-36
The List ADT…
Multi-lists…
 Linked List implementation
C1
C2
CN
S1 SM
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 using free we can release it
 In absence of pointers how would we implement
Linked Lists
 Have to simulate the above two features
Lists, Stacks, and Queues 3-38
Lists, Stacks, and Queues
1 Abstract Data Types (ADT)
2 The List ADT
3 The Stack ADT
4 The Queue ADT
Lists, Stacks, and Queues 3-39
The Stack ADT
Example
 pile of plates
1
2
bottom
top
1
2
3
bottom
top
1
bottom
top
running time?
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
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 element
from the stack
• an output operation
 Top
• examines the most recently inserted element
• an output operation
Lists, Stacks, and Queues 3-42
The Stack ADT…
empty stack
top A
top
push an element
top
push another
A
B
top
pop
A
Lists, Stacks, and Queues 3-43
The Stack ADT…
Common errors
 A Pop or Top on an empty stack is generally
considered 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 a
stack
• Singly Linked lists
• Arrays
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 the
element at the front of list
 Top operation returns the value
of the element at the front
NULL
Top of Stack
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;
};
Lists, Stacks, and Queues 3-46
The Stack ADT…
Programming details…
int
IsEmpty( Stack S )
{
return S->Next == NULL;
}
Running time?
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?
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?
Lists, Stacks, and Queues 3-49
The Stack ADT…
Programming 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?
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?
Lists, Stacks, and Queues 3-51
The Stack ADT…
Programming 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?
Lists, Stacks, and Queues 3-52
The Stack ADT…
Linked List Implementation of Stacks
 The malloc and free 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
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
Lists, Stacks, and Queues 3-54
The Stack ADT…
Array Implementation of Stacks…
 With each stack, TopOfStack is defined that stores
the array index of the top of the stack
• for an empty stack, TopOfStack is set to -1
 Push
• Increment TopOfStack by 1
• Set Stack[TopOfStack] = X
 Pop
• Set return value to Stack[TopOfStack]
• Decrement TopOfStack by 1
 These are performed in very fast constant time
Lists, Stacks, and Queues 3-55
The Stack ADT…
 On some machines, Pushes and Pops (of integers) can
be written in one machine instruction, operating on a
register with auto-increment and auto-decrement
addressing
TOS = -1
A TOS = 0
Stack[TOS]
A
B TOS = 1
Stack[TOS]
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 )
Lists, Stacks, and Queues 3-57
The Stack ADT… Programming details…
Stack
CreateStack( 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;
}
Lists, Stacks, and Queues 3-58
The Stack ADT…
Programming details
void
DisposeStack( Stack S )
{
if( S != NULL )
{
free( S->Array );
free( S );
}
}
Lists, Stacks, and Queues 3-59
The Stack ADT…
Programming details
int
IsEmpty( Stack S )
{
return S->TopOfStack == EmptyTOS;
}
Lists, Stacks, and Queues 3-60
The Stack ADT…
Programming details
void
MakeEmpty( Stack S )
{
S->TopOfStack = EmptyTOS;
}
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;
}
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 */
}
Lists, Stacks, and Queues 3-63
The Stack ADT…
Programming details
void
Pop( Stack S )
{
if( IsEmpty( S ) )
Error( "Empty stack" );
else
S->TopOfStack--;
}
Lists, Stacks, and Queues 3-64
The Stack ADT…
Programming details
ElementType
TopAndPop( Stack S )
{
if( !IsEmpty( S ) )
return S->Array[ S->TopOfStack-- ];
Error( "Empty stack" );
return 0; /* Return value used to avoid warning */
}
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 recent
preceding unmatched left bracket should be of
the same type
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 onto
the stack
 When a right bracket is encountered, stack is
popped (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 bracketed
 At the end of expression, if the stack is empty, it is
correctly bracketed otherwise, there are too many
left brackets
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 +
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?
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
RPN
Infix
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 two
operands off stack, perform operation, and
 Push the result onto the stack
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
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 push
operator onto the stack
 If input is (, then push it onto the stack
 If input is ), then pop and output all operators until
see a ( on the stack
 Pop the ( without output
 If no more input then pop and output all operators
on stack
Lists, Stacks, and Queues 3-73
The Stack ADT…
a b c * + d e * f + g * +
+
*
+ +
(
+
*
(
+
+
(
+ +
*
+
Output:
Stack:
Arrows represent
pop and output
Arrows represent
pop and output
a + b * c + (d * e + f) * g
Don’t remove an open
parentheses until a closed
parentheses
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 function
but cease to be accessible once the function
has returned ->an absolute memory address?
 To store the return address
 Stack frame = local variables + return address
Lists, Stacks, and Queues 3-75
The Stack ADT…
Function Calls…
func2(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 func1
Return Address
Parameters
Locals of func2
Return Address
stack frame
or
activation record
Call Stack
Lists, Stacks, and Queues 3-76
The Stack ADT…
 Stack in a real computer frequently grows from the
high end of your computer partition downward and
on many systems there is no checking for overflow
 program may crash
 Stack data may run into your program’s code 
corrupt
Stack data may run into your program’s data 
you may destroy your stack information
Lists, Stacks, and Queues 3-77
The Stack ADT…
 This routine which
prints out a linked list, is
perfectly legal and
actually correct
 However, if the list
consists 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
Lists, Stacks, and Queues 3-78
The Stack ADT…
 Recursion in the
above program is
called tail recursion
as the recursive call
is made at the last
line
void
PrintList (List L)
{
top:
if( L != NULL)
{
PrintElement( L->Element );
L= L->Next;
goto top;
}
}
Lists, Stacks, and Queues 3-79
Lists, Stacks, and Queues
1 Abstract Data Types (ADT)
2 The List ADT
3 The Stack ADT
4 The Queue ADT
Lists, Stacks, and Queues 3-80
The Queue ADT
 A queue is a list with the restriction that insertions
take 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
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) rear
front
Insert
(Enqueue)
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
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
Lists, Stacks, and Queues 3-84
The Queue ADT…
 To Enqueue an element X
• Increment Size and Rear
• Set Queue[Rear] =X
 To Dequeue an element
• Set the return value to Queue[Front]
• Decrement Size and increment Front
rear
front
5 2 7 1
Lists, Stacks, and Queues 3-85
The Queue ADT…
 Problem with this implementation
 After 7 Enqueues, the queue appears to be full,
since Rear is now 7, and the next Enqueue would
be in a nonexistent position
• there might only be a few elements in the
queue because several elements may have
already been dequeued
rear
front
5 2 7 1
Lists, Stacks, and Queues 3-86
The Queue ADT…
rear
front
2 4
rear front
2 4
1
rear front
2 4
1 3
rear front
2 4
1 3
Initial state
After Enqueue(1)
After Enqueue(3)
After Dequeue
Lists, Stacks, and Queues 3-87
The Queue ADT…
After Dequeue
After Dequeue
After Dequeue
rear
front
2 4
1 3
rear
front
2 4
1 3
rear front
2 4
1 3
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;
};
Lists, Stacks, and Queues 3-89
The Queue ADT…
Programming Details…
int
IsEmpty( Queue Q )
{
return Q->Size == 0;
}
Lists, Stacks, and Queues 3-90
The Queue ADT...
Programming Details…
void
MakeEmpty( Queue Q )
{
Q->Size = 0;
Q->Front = 1;
Q->Rear = 0;
}
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;
}
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;
}
}
Lists, Stacks, and Queues 3-93
Lists, Stacks, and Queues : Summary
Covered
 We have
 Learnt the concept of ADTs
 Illustrated the concept with three of the most
common ADTs
 the primary objective is to separate the
implementation of ADTs from their functions
 Lists, Stacks and Queues have their own uses as
documented through a host of examples

More Related Content

Similar to List,Stacks and Queues.pptx

computer notes - Data Structures - 32
computer notes - Data Structures - 32computer notes - Data Structures - 32
computer notes - Data Structures - 32ecomputernotes
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueRai University
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queueRai University
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queueRai University
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-listpinakspatel
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1smruti sarangi
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methodsnarmadhakin
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structuresNiraj Agarwal
 
Data Structure -List Stack Queue
Data Structure -List Stack QueueData Structure -List Stack Queue
Data Structure -List Stack Queuesurya pandian
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear listsToniyaP1
 

Similar to List,Stacks and Queues.pptx (20)

computer notes - Data Structures - 32
computer notes - Data Structures - 32computer notes - Data Structures - 32
computer notes - Data Structures - 32
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
 
lect 2-DS ALGO(online).pdf
lect 2-DS  ALGO(online).pdflect 2-DS  ALGO(online).pdf
lect 2-DS ALGO(online).pdf
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
 
Unit - 2.pdf
Unit - 2.pdfUnit - 2.pdf
Unit - 2.pdf
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
 
03-Lists.ppt
03-Lists.ppt03-Lists.ppt
03-Lists.ppt
 
Data structure
 Data structure Data structure
Data structure
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Ds notes
Ds notesDs notes
Ds notes
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1
 
Data structures
Data structures Data structures
Data structures
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
Data Structure -List Stack Queue
Data Structure -List Stack QueueData Structure -List Stack Queue
Data Structure -List Stack Queue
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
 
3.ppt
3.ppt3.ppt
3.ppt
 
3.ppt
3.ppt3.ppt
3.ppt
 

Recently uploaded

College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 

Recently uploaded (20)

College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 

List,Stacks and Queues.pptx

  • 2. Lists, Stacks, and Queues 1 Abstract Data Types (ADT) 2 The List ADT 3 The Stack ADT 4 The Queue ADT
  • 3. Lists, Stacks, and Queues Our goals: we will learn  The concept of Abstract Data Types (ADTS)  How to efficiently perform operations on lists  The Stack ADT and its use in implementing recursion  The Queue ADT and its use in operating systems and algorithm design
  • 4. Lists, Stacks, and Queues 1 Abstract Data Types (ADT) 2 The List ADT 3 The Stack ADT 4 The Queue ADT
  • 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, /
  • 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 List ADT • A set of the elements that can be integers • Operations: PrintList , MakeEmpty , Insert, Delete, FindKth
  • 7. Abstract Data Types (ADT)… Why do we call it abstract?  In an ADT’s 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
  • 8. Lists, Stacks, and Queues 1 Abstract Data Types (ADT) 2 The List ADT 3 The Stack ADT 4 The Queue ADT
  • 9. The List ADT Objects  A general list is of the form A1, A2,…, AN • where the size of the list is N • and a list of size 0 is called an empty list • Ai+1 follows Ai for i < N and • Ai-1 precedesAi for i >1 • We don’t define the predecessor of A1 or the successor of AN • The position of element Ai is i
  • 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, 12  Delete: delete an element from the list • Delete(52)  34, 12, X, 16, 12  FindKth: retrieve the element at a certain position
  • 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 -1 1 -2 6 2 -1 -2 5 -3 A1 AN
  • 12. The List ADT… Running time of the operations  The running time for PrintList and Find ? • O(N)  The running time for FindKth ? • O(1)  The running time for Insert ? • O(N)  The running time for Delete ? • O(N) are slow operations, because we have to move other elements Can we somehow avoid the linear cost of insertion and deletion?
  • 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 a pointer (called Next ) to a structure containing its successor A1 AN NULL 4 -3 -1 …….. A node in the list Pointer is a variable that contains the address where some other data are stored Conceptual view
  • 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 0 A3 992 A4 692 1000 800 712 992 692 Actual view O(N) O(N) O(N)
  • 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 NULL 4 -3 -1 5 A3 A4 A2
  • 16. The List ADT… Deletion from a Linked List  Requires one pointer change  Running time O(1) NULL A1 A 4 4 -3 -1 5 A3 delete A2
  • 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
  • 18. The List ADT… Programming Details NULL header (An empty list) NULL A1 A3 A2 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
  • 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…
  • 20. The List ADT… Programming Details… /* Return true if L is empty */ int IsEmpty( List L ) { return L->Next == NULL; } Running time?
  • 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?
  • 22. The List ADT… Programming Details… /* Return Position of X in L; NULL if not found */ Position Find( ElementType X, List L ) { Position P; /* 1*/ P = L->Next; /* 2*/ while( P != NULL && P->Element != X ) /* 3*/ P = P->Next; /* 4*/ return P; } Running time?
  • 23. 3-23 The List ADT… Programming Details… /* If X is not found, then Next field of returned value is NULL */ /* Assumes a header */ Position FindPrevious( 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?
  • 24. Lists, Stacks, and Queues 3-24 The List ADT… Programming Details…  A consequence of the free(P) command is that the address that P 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?
  • 25. Lists, Stacks, and Queues 3-25 The List ADT… Programming 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?
  • 26. Lists, Stacks, and Queues 3-26 The List ADT… Common errors  The most common error you will encounter is that your program will crash with message, such as “memory access violation” , or “segmentation violation”  pointer variable contains a bogus address  pointer is not properly initialized  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?
  • 27. 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 malloc to create a structure  It takes as an argument the number of bytes to be allocated and returns a pointer to 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; } }
  • 28. Lists, Stacks, and Queues 3-28 The List ADT… Problems with Linked Lists or Singly Linked Lists  finding the successor of an item easy what about the predecessor ?  we can’t traverse singly linked lists backwards  So, circular linked lists and doubly linked lists were invented NULL A1 A3 A2 header
  • 29. 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 NULL A3 A4 A2 A1 NULL
  • 30. Lists, Stacks, and Queues 3-30 The List ADT… Circularly Linked Lists previous element next A2 A4 A3 A1 A double circularly linked list
  • 31. 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 i N i i x A f(x)    0 9 4 5 7 2 3 4 5     x x x x 1 -7 5 -4 0 9
  • 32. Lists, Stacks, and Queues 3-32 The List ADT… Implementation  If most of the coefficients of the polynomial are nonzero, we can use a simple array to store them typedef struct { int CoeffArray[ MaxDegree + 1 ]; int HighPower; } *Polynomial; void ZeroPolynomial( Polynomial Poly ) { int i; for( i = 0; i <= MaxDegree; i++ ) Poly->CoeffArray[ i ] = 0; Poly->HighPower = 0; }
  • 33. Lists, Stacks, and Queues 3-33 The List ADT… Implementation  Ignore the time to initialize the output polynomials to zero, then running time is proportional to the product of the degree of the two input polynomials 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 <= Poly1->HighPower; i++ ) for( j = 0; j <= Poly2->HighPower; j++ ) PolyProd->CoeffArray[ i + j ] += Poly1->CoeffArray[ i ] * Poly2->CoeffArray[ j ]; }
  • 34. Lists, Stacks, and Queues 3-34 The List ADT…  Singly Linked lists would definitely be a good alternative to arrays for sparse polynomials 5 11 2 3 ) ( 1 5 10 ) ( 1492 1990 2 14 1000 1        x x x x P x x x P 10 1000 5 14 1 0 P1 NULL 3 1990 1492 -2 11 1 5 0 P2 NULL Each node has the coefficient, the exponent, and the pointer to next
  • 35. 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……………………………..
  • 36. Lists, Stacks, and Queues 3-36 The List ADT… Multi-lists…  Linked List implementation C1 C2 CN S1 SM
  • 37. 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 using free we can release it  In absence of pointers how would we implement Linked Lists  Have to simulate the above two features
  • 38. Lists, Stacks, and Queues 3-38 Lists, Stacks, and Queues 1 Abstract Data Types (ADT) 2 The List ADT 3 The Stack ADT 4 The Queue ADT
  • 39. Lists, Stacks, and Queues 3-39 The Stack ADT Example  pile of plates 1 2 bottom top 1 2 3 bottom top 1 bottom top running time?
  • 40. 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
  • 41. 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 element from the stack • an output operation  Top • examines the most recently inserted element • an output operation
  • 42. Lists, Stacks, and Queues 3-42 The Stack ADT… empty stack top A top push an element top push another A B top pop A
  • 43. Lists, Stacks, and Queues 3-43 The Stack ADT… Common errors  A Pop or Top on an empty stack is generally considered 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 a stack • Singly Linked lists • Arrays
  • 44. 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 the element at the front of list  Top operation returns the value of the element at the front NULL Top of Stack
  • 45. 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; };
  • 46. Lists, Stacks, and Queues 3-46 The Stack ADT… Programming details… int IsEmpty( Stack S ) { return S->Next == NULL; } Running time?
  • 47. 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?
  • 48. 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?
  • 49. Lists, Stacks, and Queues 3-49 The Stack ADT… Programming 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?
  • 50. 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?
  • 51. Lists, Stacks, and Queues 3-51 The Stack ADT… Programming 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?
  • 52. Lists, Stacks, and Queues 3-52 The Stack ADT… Linked List Implementation of Stacks  The malloc and free 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
  • 53. 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
  • 54. Lists, Stacks, and Queues 3-54 The Stack ADT… Array Implementation of Stacks…  With each stack, TopOfStack is defined that stores the array index of the top of the stack • for an empty stack, TopOfStack is set to -1  Push • Increment TopOfStack by 1 • Set Stack[TopOfStack] = X  Pop • Set return value to Stack[TopOfStack] • Decrement TopOfStack by 1  These are performed in very fast constant time
  • 55. Lists, Stacks, and Queues 3-55 The Stack ADT…  On some machines, Pushes and Pops (of integers) can be written in one machine instruction, operating on a register with auto-increment and auto-decrement addressing TOS = -1 A TOS = 0 Stack[TOS] A B TOS = 1 Stack[TOS]
  • 56. 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 )
  • 57. Lists, Stacks, and Queues 3-57 The Stack ADT… Programming details… Stack CreateStack( 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; }
  • 58. Lists, Stacks, and Queues 3-58 The Stack ADT… Programming details void DisposeStack( Stack S ) { if( S != NULL ) { free( S->Array ); free( S ); } }
  • 59. Lists, Stacks, and Queues 3-59 The Stack ADT… Programming details int IsEmpty( Stack S ) { return S->TopOfStack == EmptyTOS; }
  • 60. Lists, Stacks, and Queues 3-60 The Stack ADT… Programming details void MakeEmpty( Stack S ) { S->TopOfStack = EmptyTOS; }
  • 61. 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; }
  • 62. 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 */ }
  • 63. Lists, Stacks, and Queues 3-63 The Stack ADT… Programming details void Pop( Stack S ) { if( IsEmpty( S ) ) Error( "Empty stack" ); else S->TopOfStack--; }
  • 64. Lists, Stacks, and Queues 3-64 The Stack ADT… Programming details ElementType TopAndPop( Stack S ) { if( !IsEmpty( S ) ) return S->Array[ S->TopOfStack-- ]; Error( "Empty stack" ); return 0; /* Return value used to avoid warning */ }
  • 65. 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 recent preceding unmatched left bracket should be of the same type
  • 66. 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 onto the stack  When a right bracket is encountered, stack is popped (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 bracketed  At the end of expression, if the stack is empty, it is correctly bracketed otherwise, there are too many left brackets
  • 67. 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 +
  • 68. 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?
  • 69. 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 RPN Infix
  • 70. 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 two operands off stack, perform operation, and  Push the result onto the stack
  • 71. 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
  • 72. 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 push operator onto the stack  If input is (, then push it onto the stack  If input is ), then pop and output all operators until see a ( on the stack  Pop the ( without output  If no more input then pop and output all operators on stack
  • 73. Lists, Stacks, and Queues 3-73 The Stack ADT… a b c * + d e * f + g * + + * + + ( + * ( + + ( + + * + Output: Stack: Arrows represent pop and output Arrows represent pop and output a + b * c + (d * e + f) * g Don’t remove an open parentheses until a closed parentheses
  • 74. 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 function but cease to be accessible once the function has returned ->an absolute memory address?  To store the return address  Stack frame = local variables + return address
  • 75. Lists, Stacks, and Queues 3-75 The Stack ADT… Function Calls… func2(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 func1 Return Address Parameters Locals of func2 Return Address stack frame or activation record Call Stack
  • 76. Lists, Stacks, and Queues 3-76 The Stack ADT…  Stack in a real computer frequently grows from the high end of your computer partition downward and on many systems there is no checking for overflow  program may crash  Stack data may run into your program’s code  corrupt Stack data may run into your program’s data  you may destroy your stack information
  • 77. Lists, Stacks, and Queues 3-77 The Stack ADT…  This routine which prints out a linked list, is perfectly legal and actually correct  However, if the list consists 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
  • 78. Lists, Stacks, and Queues 3-78 The Stack ADT…  Recursion in the above program is called tail recursion as the recursive call is made at the last line void PrintList (List L) { top: if( L != NULL) { PrintElement( L->Element ); L= L->Next; goto top; } }
  • 79. Lists, Stacks, and Queues 3-79 Lists, Stacks, and Queues 1 Abstract Data Types (ADT) 2 The List ADT 3 The Stack ADT 4 The Queue ADT
  • 80. Lists, Stacks, and Queues 3-80 The Queue ADT  A queue is a list with the restriction that insertions take 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
  • 81. 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) rear front Insert (Enqueue)
  • 82. 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
  • 83. 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
  • 84. Lists, Stacks, and Queues 3-84 The Queue ADT…  To Enqueue an element X • Increment Size and Rear • Set Queue[Rear] =X  To Dequeue an element • Set the return value to Queue[Front] • Decrement Size and increment Front rear front 5 2 7 1
  • 85. Lists, Stacks, and Queues 3-85 The Queue ADT…  Problem with this implementation  After 7 Enqueues, the queue appears to be full, since Rear is now 7, and the next Enqueue would be in a nonexistent position • there might only be a few elements in the queue because several elements may have already been dequeued rear front 5 2 7 1
  • 86. Lists, Stacks, and Queues 3-86 The Queue ADT… rear front 2 4 rear front 2 4 1 rear front 2 4 1 3 rear front 2 4 1 3 Initial state After Enqueue(1) After Enqueue(3) After Dequeue
  • 87. Lists, Stacks, and Queues 3-87 The Queue ADT… After Dequeue After Dequeue After Dequeue rear front 2 4 1 3 rear front 2 4 1 3 rear front 2 4 1 3
  • 88. 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; };
  • 89. Lists, Stacks, and Queues 3-89 The Queue ADT… Programming Details… int IsEmpty( Queue Q ) { return Q->Size == 0; }
  • 90. Lists, Stacks, and Queues 3-90 The Queue ADT... Programming Details… void MakeEmpty( Queue Q ) { Q->Size = 0; Q->Front = 1; Q->Rear = 0; }
  • 91. 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; }
  • 92. 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; } }
  • 93. Lists, Stacks, and Queues 3-93 Lists, Stacks, and Queues : Summary Covered  We have  Learnt the concept of ADTs  Illustrated the concept with three of the most common ADTs  the primary objective is to separate the implementation of ADTs from their functions  Lists, Stacks and Queues have their own uses as documented through a host of examples