Stacks
• Stack: what is it?
• ADT
• Applications
• Implementation(s)
ABSTRACT DATA TYPE
A list could be described by the type of information that it holds and by the
operations that can be performed on the list. In this sense the list is an example of
an ABSTRACT DATA TYPE. It is possible to think about a list without knowing the
details of how it is implemented. An ABSTRACT DATA TYPE (ADT) has a set of rules
(behaviour) and attributes imposed upon it that reflect a real world object.
Eg. A waiting queue at a bank or cinema has some clearly defined rules:
• The queue contains customers.
• Customers join the rear of the queue.
• Customers leave from the front of the queue.
• Customers leave the queue in the order in which they joined it.
• The queue can be empty.
It is quite sensible to talk about the abstract properties of a queue without
concerning ourselves about the implementation of a computer model for the
queue.
LINEAR DATA STRUCTURES
All data structures introduced thus far are
special subclasses of linear lists. There are two
ways of storing data structures in the
computer’s memory. The first of these
storage-allocation methods, which takes
advantage of the one-dimensional property of
the computer’s memory, is called sequential
allocation.
LINEAR DATA STRUCTURES
The second allocation method, which is based on the
storage of the address or location of each element in
the list, is known as linked allocation. Both methods
of allocation are discussed in detail in this section.
Several subclasses of linear lists can be defined. The
most important of these subclasses are called stacks
and queues.
LINEAR DATA STRUCTURES (STACK)
One of the most important subclasses of linear lists is
the family of stack structure. In this section we first
introduce the concepts associated with this subclass
of linear structures. Next, several important
operations, such as insertion and deletion, for the
stack structure are given. In particular, we describe
the implementation of these operations for a stack
that is represented by a vector.
Stack Abstract Data Type (ADT)
• A stack is a special case of a list.
• Rather than being allowed to insert a new item into the list at
any place, additions to a stack are restricted to one end
identified as the top of the stack.
• Deletions from the stack are also restricted to the top of the
stack.
• Usually, only the item at the top of the stack is accessible to
someone using the stack ADT.
• A stack is often referred to as a FILO (First In Last Out) list. The
stack only allows addition and removal from of the top
element so the order of removal is the opposite to that of
addition.
What is a stack?
• Stores a set of elements in a particular order
• Stack principle: LAST IN FIRST OUT
• = LIFO
• It means: the last element inserted is the first
one to be removed
• Example
• Which is the first element to pick up?
Stack
Last In First Out
B
A
D
C
B
A
C
B
A
D
C
B
A
E
D
C
B
A
top
top
top
top
top
A
Stack
Stack Applications
• Real life
– Pile of books
– Plate trays
• More applications related to computer
science
– Program execution stack (read more from your
text)
– Evaluating expressions
Application
• Word processors, editors, etc:
– Can implement undo operations
• At runtime:
– Runtime system uses a stack to keep track of
function calls and returns, which variables are
currently accessible, etc(activation records)
Applications of Stack
• Reversing the string
– push each character on to a stack as it is read.
– When the line is finished, we then pop characters
off the stack, and they will come off in the reverse
order.
Stack Operations
Stack Create an empty stack
~Stack Destroy an existing stack
isEmpty Determine whether the stack is empty
isFull Determine whether the stack is full
push Add an item to the top of the stack
pop Remove the item most recently added
Peek/top Retrieve the item most recently added
Clear Clears the contents of stack
Stack Implementation
• Static Implementation
(Using arrays)
• Dynamic Implementation
(Using dynamic lists)
Stack Implementation Using Arrays
• For the static implementation of stack an array
will be used.
• This array will hold the stack elements.
• The top of a stack is represented by an integer
type variable which contains the index of an
array containing top element of a stack.
Stack Implementation Using Arrays
4
3
2
1
0
Empty stack
StackSize = 5
top = -1
70
1
2
3
4
top
Push 7
70
81
2
3
4
top
Push 8
Push 9
70
81
92
3
4
top
Push 4
70
81
92
43
4
top
Push 5
70
81
92
43
54
top
top = StackSize – 1,
Stack is full,
We can’t push more elements.
Stack using an Array
top
2
5
7
1
2 5 7 1
0 1 32 4
top = 3
Stack Implementation Using Arrays
push(element)
{
if (top == StackSize – 1)
cout<<“stack is full”;
else
Stack[++top] = element;
}
Stack Implementation Using Arrays
4
3
2
1
0
Empty stack
top = -1
We can’t pop mpre
elements
70
1
2
3
4
top
Pop
70
81
2
3
4
top
70
81
92
3
4
top
70
81
92
43
4
top
70
81
92
43
54
top
top = StackSize – 1,
Stack is full,
We can’t push more elements.
Pop
Pop Pop Pop
Stack Implementation Using Arrays
pop()
{
if (top == –1)
cout<<“stack is empty”;
else
return Stack[top--];
}
Stack Implementation Using Arrays
topElement() //returns the top element of stack
//without removing it.
{
if (top == –1)
cout<<“stack is empty”;
else
return Stack[top];
}
Stack Implementation Using Arrays
isEmpty() //checks stack is empty or not
{
if (top == –1)
return true
else
return false
}
Stack Implementation Using Arrays
template <class Element_Type>
class Stack
{
private:
/* This variable is used to indicate stack is
full or not*/
unsigned int Full_Stack;
/* This variable is used to indicate top of
the stack */
int Top_of_Stack;
/* This pointer points to the array which
behaves as stack, the space for this array is
allocated dynamically */
Element_Type *Stack_Array
Continue on next slide…
Stack Implementation Using Arrays
//This constructor creates a stack.
Stack(unsigned int Max_Size)
{
Full_Stack = Max_Size;
Top_of_Stack = -1;
Stack_Array = new Element_Type[Max_Size];
}
/* This Destructor frees the dynamically allocated
space to the array */
~Stack()
{
delete Stack_Array;
}
Continue on next slide…
Stack Implementation Using Arrays
/*This function Return TRUE if the stack is full, FALSE otherwise.*/
bool Is_Full()
{ if (Top_of_Stack == Full_Stack-1)
returns True;
else
returns False;
}
/*This function Return TRUE if the stack is empty, FALSE otherwise.*/
bool Is_Empty()
{ if(Top_of_Stack == -1)
returns True;
else
returns False;
}
Continue on next slide…
Stack Implementation Using Arrays
// If stack is not full then push an element x in it
void Push(Element_Type x)
{ if(is_Full())
cout<<“stack is full”;
else
Stack_Array[++Top_of_Stack] = x;
}
//if Stack is not empty then pop an element form it
Element_Type pop()
{ if(is_Empty())
cout<<“stack is empty”;
else
return Stack_Array[Top_of_Stack--];
}
Continue on next slide…
Stack Implementation Using Arrays
// This function makes the stack empty
void Make_Empty()
{ Top_of_Stack = -1;
}
/* This function returns the top element of stack */
Element_Type Top()
{
if(is_Empty())
cout<<“stack is emepty”;
else
return Stack_Array[Top_of_Stack];
}
};
Stack Using Linked List
• We can avoid the size limitation of a stack
implemented with an array by using a
linked list to hold the stack elements.
• As with array, however, we need to decide
where to insert elements in the list and
where to delete them so that push and pop
will run the fastest.
Stack Using Linked List
• For a singly-linked list, insert at start or end
takes constant time using the head and current
pointers respectively.
• Removing an element at the start is constant
time but removal at the end required traversing
the list to the node one before the last.
• Make sense to place stack elements at the start
of the list because insert and removal are
constant time.
Stack Using Linked List
• No need for the current pointer; head is enough.
top
2
5
7
1
1 7 5 2
head
Stack Operation: List
int pop()
{
int x = head->get();
Node* p = head;
head = head->getNext();
delete p;
return x;
}
top
2
5
7
1 7 5 2
head
Stack Operation: List
void push(int x)
{
Node* newNode = new Node();
newNode->set(x);
newNode->setNext(head);
head = newNode;
}
top
2
5
7
9
7 5 2
head
push(9)
9
newNode
Stack Operation: List
int top()
{
return head->get();
}
int IsEmpty()
{
return ( head == NULL );
}
• All four operations take constant time.
Stack: Array or List
• Since both implementations support stack
operations in constant time, any reason to
choose one over the other?
• Allocating and deallocating memory for list
nodes does take more time than preallocated
array.
• List uses only as much memory as required by
the nodes; array requires allocation ahead of
time.
• List pointers (head, next) require extra memory.
• Array has an upper limit; List is limited by
dynamic memory allocation.
Use of Stack
• Example of use: prefix, infix, postfix
expressions.
• Consider the expression A+B: we think of
applying the operator “+” to the operands
A and B.
• “+” is termed a binary operator: it takes
two operands.
• Writing the sum as A+B is called the infix
form of the expression.
Prefix, Infix, Postfix
• Two other ways of writing the expression
are
+ A B prefix
A B + postfix
• The prefixes “pre” and “post” refer to the
position of the operator with respect to the
two operands.
Prefix, Infix, Postfix
• Consider the infix expression
A + B * C
• We “know” that multiplication is done
before addition.
• The expression is interpreted as
A + ( B * C )
• Multiplication has precedence over
addition.
Prefix, Infix, Postfix
• Conversion to postfix
A + ( B * C ) infix form
Prefix, Infix, Postfix
• Conversion to postfix
A + ( B * C ) infix form
A + ( B C * ) convert multiplication
Prefix, Infix, Postfix
• Conversion to postfix
A + ( B * C ) infix form
A + ( B C * ) convert multiplication
A ( B C * ) + convert addition
Prefix, Infix, Postfix
• Conversion to postfix
A + ( B * C ) infix form
A + ( B C * ) convert multiplication
A ( B C * ) + convert addition
A B C * + postfix form
Prefix, Infix, Postfix
• Conversion to postfix
(A + B ) * C infix form
Prefix, Infix, Postfix
• Conversion to postfix
(A + B ) * C infix form
( A B + ) * C convert addition
Prefix, Infix, Postfix
• Conversion to postfix
(A + B ) * C infix form
( A B + ) * C convert addition
( A B + ) C * convert multiplication
Prefix, Infix, Postfix
• Conversion to postfix
(A + B ) * C infix form
( A B + ) * C convert addition
( A B + ) C * convert multiplication
A B + C * postfix form
Precedence of Operators
• The five binary operators are: addition,
subtraction, multiplication, division and
exponentiation.
• The order of precedence is (highest to
lowest)
• Exponentiation 
• Multiplication/division *, /
• Addition/subtraction +, -
Precedence of Operators
• For operators of same precedence, the
left-to-right rule applies:
A+B+C means (A+B)+C.
• For exponentiation, the right-to-left rule
applies
A  B  C means A  ( B  C )
Infix to Postfix
Infix Postfix
A + B A B +
12 + 60 – 23 12 60 + 23 –
(A + B)*(C – D ) A B + C D – *
A  B * C – D + E/F A B  C*D – E F/+

Stack in Sata Structure

  • 1.
    Stacks • Stack: whatis it? • ADT • Applications • Implementation(s)
  • 2.
    ABSTRACT DATA TYPE Alist could be described by the type of information that it holds and by the operations that can be performed on the list. In this sense the list is an example of an ABSTRACT DATA TYPE. It is possible to think about a list without knowing the details of how it is implemented. An ABSTRACT DATA TYPE (ADT) has a set of rules (behaviour) and attributes imposed upon it that reflect a real world object. Eg. A waiting queue at a bank or cinema has some clearly defined rules: • The queue contains customers. • Customers join the rear of the queue. • Customers leave from the front of the queue. • Customers leave the queue in the order in which they joined it. • The queue can be empty. It is quite sensible to talk about the abstract properties of a queue without concerning ourselves about the implementation of a computer model for the queue.
  • 3.
    LINEAR DATA STRUCTURES Alldata structures introduced thus far are special subclasses of linear lists. There are two ways of storing data structures in the computer’s memory. The first of these storage-allocation methods, which takes advantage of the one-dimensional property of the computer’s memory, is called sequential allocation.
  • 4.
    LINEAR DATA STRUCTURES Thesecond allocation method, which is based on the storage of the address or location of each element in the list, is known as linked allocation. Both methods of allocation are discussed in detail in this section. Several subclasses of linear lists can be defined. The most important of these subclasses are called stacks and queues.
  • 5.
    LINEAR DATA STRUCTURES(STACK) One of the most important subclasses of linear lists is the family of stack structure. In this section we first introduce the concepts associated with this subclass of linear structures. Next, several important operations, such as insertion and deletion, for the stack structure are given. In particular, we describe the implementation of these operations for a stack that is represented by a vector.
  • 6.
    Stack Abstract DataType (ADT) • A stack is a special case of a list. • Rather than being allowed to insert a new item into the list at any place, additions to a stack are restricted to one end identified as the top of the stack. • Deletions from the stack are also restricted to the top of the stack. • Usually, only the item at the top of the stack is accessible to someone using the stack ADT. • A stack is often referred to as a FILO (First In Last Out) list. The stack only allows addition and removal from of the top element so the order of removal is the opposite to that of addition.
  • 7.
    What is astack? • Stores a set of elements in a particular order • Stack principle: LAST IN FIRST OUT • = LIFO • It means: the last element inserted is the first one to be removed • Example • Which is the first element to pick up?
  • 8.
  • 9.
    Last In FirstOut B A D C B A C B A D C B A E D C B A top top top top top A
  • 10.
  • 11.
    Stack Applications • Reallife – Pile of books – Plate trays • More applications related to computer science – Program execution stack (read more from your text) – Evaluating expressions
  • 12.
    Application • Word processors,editors, etc: – Can implement undo operations • At runtime: – Runtime system uses a stack to keep track of function calls and returns, which variables are currently accessible, etc(activation records)
  • 13.
    Applications of Stack •Reversing the string – push each character on to a stack as it is read. – When the line is finished, we then pop characters off the stack, and they will come off in the reverse order.
  • 14.
    Stack Operations Stack Createan empty stack ~Stack Destroy an existing stack isEmpty Determine whether the stack is empty isFull Determine whether the stack is full push Add an item to the top of the stack pop Remove the item most recently added Peek/top Retrieve the item most recently added Clear Clears the contents of stack
  • 15.
    Stack Implementation • StaticImplementation (Using arrays) • Dynamic Implementation (Using dynamic lists)
  • 16.
    Stack Implementation UsingArrays • For the static implementation of stack an array will be used. • This array will hold the stack elements. • The top of a stack is represented by an integer type variable which contains the index of an array containing top element of a stack.
  • 17.
    Stack Implementation UsingArrays 4 3 2 1 0 Empty stack StackSize = 5 top = -1 70 1 2 3 4 top Push 7 70 81 2 3 4 top Push 8 Push 9 70 81 92 3 4 top Push 4 70 81 92 43 4 top Push 5 70 81 92 43 54 top top = StackSize – 1, Stack is full, We can’t push more elements.
  • 18.
    Stack using anArray top 2 5 7 1 2 5 7 1 0 1 32 4 top = 3
  • 19.
    Stack Implementation UsingArrays push(element) { if (top == StackSize – 1) cout<<“stack is full”; else Stack[++top] = element; }
  • 20.
    Stack Implementation UsingArrays 4 3 2 1 0 Empty stack top = -1 We can’t pop mpre elements 70 1 2 3 4 top Pop 70 81 2 3 4 top 70 81 92 3 4 top 70 81 92 43 4 top 70 81 92 43 54 top top = StackSize – 1, Stack is full, We can’t push more elements. Pop Pop Pop Pop
  • 21.
    Stack Implementation UsingArrays pop() { if (top == –1) cout<<“stack is empty”; else return Stack[top--]; }
  • 22.
    Stack Implementation UsingArrays topElement() //returns the top element of stack //without removing it. { if (top == –1) cout<<“stack is empty”; else return Stack[top]; }
  • 23.
    Stack Implementation UsingArrays isEmpty() //checks stack is empty or not { if (top == –1) return true else return false }
  • 24.
    Stack Implementation UsingArrays template <class Element_Type> class Stack { private: /* This variable is used to indicate stack is full or not*/ unsigned int Full_Stack; /* This variable is used to indicate top of the stack */ int Top_of_Stack; /* This pointer points to the array which behaves as stack, the space for this array is allocated dynamically */ Element_Type *Stack_Array Continue on next slide…
  • 25.
    Stack Implementation UsingArrays //This constructor creates a stack. Stack(unsigned int Max_Size) { Full_Stack = Max_Size; Top_of_Stack = -1; Stack_Array = new Element_Type[Max_Size]; } /* This Destructor frees the dynamically allocated space to the array */ ~Stack() { delete Stack_Array; } Continue on next slide…
  • 26.
    Stack Implementation UsingArrays /*This function Return TRUE if the stack is full, FALSE otherwise.*/ bool Is_Full() { if (Top_of_Stack == Full_Stack-1) returns True; else returns False; } /*This function Return TRUE if the stack is empty, FALSE otherwise.*/ bool Is_Empty() { if(Top_of_Stack == -1) returns True; else returns False; } Continue on next slide…
  • 27.
    Stack Implementation UsingArrays // If stack is not full then push an element x in it void Push(Element_Type x) { if(is_Full()) cout<<“stack is full”; else Stack_Array[++Top_of_Stack] = x; } //if Stack is not empty then pop an element form it Element_Type pop() { if(is_Empty()) cout<<“stack is empty”; else return Stack_Array[Top_of_Stack--]; } Continue on next slide…
  • 28.
    Stack Implementation UsingArrays // This function makes the stack empty void Make_Empty() { Top_of_Stack = -1; } /* This function returns the top element of stack */ Element_Type Top() { if(is_Empty()) cout<<“stack is emepty”; else return Stack_Array[Top_of_Stack]; } };
  • 29.
    Stack Using LinkedList • We can avoid the size limitation of a stack implemented with an array by using a linked list to hold the stack elements. • As with array, however, we need to decide where to insert elements in the list and where to delete them so that push and pop will run the fastest.
  • 30.
    Stack Using LinkedList • For a singly-linked list, insert at start or end takes constant time using the head and current pointers respectively. • Removing an element at the start is constant time but removal at the end required traversing the list to the node one before the last. • Make sense to place stack elements at the start of the list because insert and removal are constant time.
  • 31.
    Stack Using LinkedList • No need for the current pointer; head is enough. top 2 5 7 1 1 7 5 2 head
  • 32.
    Stack Operation: List intpop() { int x = head->get(); Node* p = head; head = head->getNext(); delete p; return x; } top 2 5 7 1 7 5 2 head
  • 33.
    Stack Operation: List voidpush(int x) { Node* newNode = new Node(); newNode->set(x); newNode->setNext(head); head = newNode; } top 2 5 7 9 7 5 2 head push(9) 9 newNode
  • 34.
    Stack Operation: List inttop() { return head->get(); } int IsEmpty() { return ( head == NULL ); } • All four operations take constant time.
  • 35.
    Stack: Array orList • Since both implementations support stack operations in constant time, any reason to choose one over the other? • Allocating and deallocating memory for list nodes does take more time than preallocated array. • List uses only as much memory as required by the nodes; array requires allocation ahead of time. • List pointers (head, next) require extra memory. • Array has an upper limit; List is limited by dynamic memory allocation.
  • 36.
    Use of Stack •Example of use: prefix, infix, postfix expressions. • Consider the expression A+B: we think of applying the operator “+” to the operands A and B. • “+” is termed a binary operator: it takes two operands. • Writing the sum as A+B is called the infix form of the expression.
  • 37.
    Prefix, Infix, Postfix •Two other ways of writing the expression are + A B prefix A B + postfix • The prefixes “pre” and “post” refer to the position of the operator with respect to the two operands.
  • 38.
    Prefix, Infix, Postfix •Consider the infix expression A + B * C • We “know” that multiplication is done before addition. • The expression is interpreted as A + ( B * C ) • Multiplication has precedence over addition.
  • 39.
    Prefix, Infix, Postfix •Conversion to postfix A + ( B * C ) infix form
  • 40.
    Prefix, Infix, Postfix •Conversion to postfix A + ( B * C ) infix form A + ( B C * ) convert multiplication
  • 41.
    Prefix, Infix, Postfix •Conversion to postfix A + ( B * C ) infix form A + ( B C * ) convert multiplication A ( B C * ) + convert addition
  • 42.
    Prefix, Infix, Postfix •Conversion to postfix A + ( B * C ) infix form A + ( B C * ) convert multiplication A ( B C * ) + convert addition A B C * + postfix form
  • 43.
    Prefix, Infix, Postfix •Conversion to postfix (A + B ) * C infix form
  • 44.
    Prefix, Infix, Postfix •Conversion to postfix (A + B ) * C infix form ( A B + ) * C convert addition
  • 45.
    Prefix, Infix, Postfix •Conversion to postfix (A + B ) * C infix form ( A B + ) * C convert addition ( A B + ) C * convert multiplication
  • 46.
    Prefix, Infix, Postfix •Conversion to postfix (A + B ) * C infix form ( A B + ) * C convert addition ( A B + ) C * convert multiplication A B + C * postfix form
  • 47.
    Precedence of Operators •The five binary operators are: addition, subtraction, multiplication, division and exponentiation. • The order of precedence is (highest to lowest) • Exponentiation  • Multiplication/division *, / • Addition/subtraction +, -
  • 48.
    Precedence of Operators •For operators of same precedence, the left-to-right rule applies: A+B+C means (A+B)+C. • For exponentiation, the right-to-left rule applies A  B  C means A  ( B  C )
  • 49.
    Infix to Postfix InfixPostfix A + B A B + 12 + 60 – 23 12 60 + 23 – (A + B)*(C – D ) A B + C D – * A  B * C – D + E/F A B  C*D – E F/+