SlideShare a Scribd company logo
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/+

More Related Content

PPTX
STACKS IN DATASTRUCTURE
PPTX
My lecture stack_queue_operation
PPT
Stacks, Queues, Deques
PPT
PPT
stack and queue array implementation in java.
PPT
Queue AS an ADT (Abstract Data Type)
PPT
Queue in Data Structure
PPTX
Stacks and Queue - Data Structures
STACKS IN DATASTRUCTURE
My lecture stack_queue_operation
Stacks, Queues, Deques
stack and queue array implementation in java.
Queue AS an ADT (Abstract Data Type)
Queue in Data Structure
Stacks and Queue - Data Structures

What's hot (20)

PPTX
Stacks in c++
PPTX
Stack Data Structure
PDF
PPTX
Queues in C++
PPT
Stack a Data Structure
PDF
STACK ( LIFO STRUCTURE) - Data Structure
PPTX
Project of data structure
PPTX
Queue ppt
PPT
PPTX
Stack project
PPSX
Data structure stack&queue basics
PPT
Queue data structure
PPTX
The Stack And Recursion
PPT
Stack & queue
PPTX
queue & its applications
PPT
Stacks overview with its applications
PPTX
PPTX
Stack - Data Structure
PPSX
Data Structure (Queue)
Stacks in c++
Stack Data Structure
Queues in C++
Stack a Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
Project of data structure
Queue ppt
Stack project
Data structure stack&queue basics
Queue data structure
The Stack And Recursion
Stack & queue
queue & its applications
Stacks overview with its applications
Stack - Data Structure
Data Structure (Queue)
Ad

Viewers also liked (20)

PDF
Preparation Data Structures 03 abstract data_types
PPT
Lec3
ODP
Chapter03
PPT
Algo>Abstract data type
PDF
Data structure circular list
PDF
10 generics a-4_in_1
PPT
Abstract data types
PDF
Abstract Data Types
PPTX
Data structures1
PDF
It6601 mobile computing unit 4 questions
PPTX
Screenless display
PDF
IT6601 Mobile Computing
PPTX
PPTX
Double linked list
PPTX
Growing OpenStack at TWC, 3rd Speaker
PPTX
Bipolar disorder
PPTX
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
PPTX
IT6601 MOBILE COMPUTING UNIT1
PPSX
Data Structure (Circular Linked List)
PDF
IT6601 MOBILE COMPUTING
Preparation Data Structures 03 abstract data_types
Lec3
Chapter03
Algo>Abstract data type
Data structure circular list
10 generics a-4_in_1
Abstract data types
Abstract Data Types
Data structures1
It6601 mobile computing unit 4 questions
Screenless display
IT6601 Mobile Computing
Double linked list
Growing OpenStack at TWC, 3rd Speaker
Bipolar disorder
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
IT6601 MOBILE COMPUTING UNIT1
Data Structure (Circular Linked List)
IT6601 MOBILE COMPUTING
Ad

Similar to Stack in Sata Structure (20)

PDF
Chapter 5 Stack and Queue.pdf
PPTX
Stack and its applications
PPT
Stack queue
PPT
Stack queue
PPT
Stack queue
PPT
Stack queue
PPT
Stack queue
PPT
Stack queue
PPT
Stack queue
PPTX
Data structure
PPT
Lecture5
PPTX
Unit II - LINEAR DATA STRUCTURES
PPTX
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
PPT
Lec 4 Stack of Data Structures & Algorithms
PPTX
Abscddnddmdkwkkstack implementation.pptx
PPT
week 7,8,10,11 alll files included from .ppt
PDF
Chapter 4 stack
PPTX
Introduction to information about Data Structure.pptx
PPTX
5.-Stacks.pptx
PPT
Lecture 2c stacks
Chapter 5 Stack and Queue.pdf
Stack and its applications
Stack queue
Stack queue
Stack queue
Stack queue
Stack queue
Stack queue
Stack queue
Data structure
Lecture5
Unit II - LINEAR DATA STRUCTURES
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
Lec 4 Stack of Data Structures & Algorithms
Abscddnddmdkwkkstack implementation.pptx
week 7,8,10,11 alll files included from .ppt
Chapter 4 stack
Introduction to information about Data Structure.pptx
5.-Stacks.pptx
Lecture 2c stacks

Recently uploaded (20)

PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Cell Types and Its function , kingdom of life
PDF
Business Ethics Teaching Materials for college
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Institutional Correction lecture only . . .
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Cell Structure & Organelles in detailed.
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Anesthesia in Laparoscopic Surgery in India
Cell Types and Its function , kingdom of life
Business Ethics Teaching Materials for college
Microbial disease of the cardiovascular and lymphatic systems
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Final Presentation General Medicine 03-08-2024.pptx
Microbial diseases, their pathogenesis and prophylaxis
O7-L3 Supply Chain Operations - ICLT Program
PPH.pptx obstetrics and gynecology in nursing
VCE English Exam - Section C Student Revision Booklet
Institutional Correction lecture only . . .
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
O5-L3 Freight Transport Ops (International) V1.pdf
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Basic Mud Logging Guide for educational purpose
Cell Structure & Organelles in detailed.
human mycosis Human fungal infections are called human mycosis..pptx

Stack in Sata Structure

  • 1. Stacks • Stack: what is it? • ADT • Applications • Implementation(s)
  • 2. 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.
  • 3. 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.
  • 4. 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.
  • 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 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.
  • 7. 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?
  • 9. 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
  • 10. Stack
  • 11. 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
  • 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 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
  • 15. Stack Implementation • Static Implementation (Using arrays) • Dynamic Implementation (Using dynamic lists)
  • 16. 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.
  • 17. 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.
  • 18. Stack using an Array top 2 5 7 1 2 5 7 1 0 1 32 4 top = 3
  • 19. Stack Implementation Using Arrays push(element) { if (top == StackSize – 1) cout<<“stack is full”; else Stack[++top] = element; }
  • 20. 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
  • 21. Stack Implementation Using Arrays pop() { if (top == –1) cout<<“stack is empty”; else return Stack[top--]; }
  • 22. 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]; }
  • 23. Stack Implementation Using Arrays isEmpty() //checks stack is empty or not { if (top == –1) return true else return false }
  • 24. 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…
  • 25. 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…
  • 26. 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…
  • 27. 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…
  • 28. 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]; } };
  • 29. 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.
  • 30. 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.
  • 31. Stack Using Linked List • No need for the current pointer; head is enough. top 2 5 7 1 1 7 5 2 head
  • 32. 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
  • 33. 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
  • 34. Stack Operation: List int top() { return head->get(); } int IsEmpty() { return ( head == NULL ); } • All four operations take constant time.
  • 35. 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.
  • 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 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/+