SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Downloaden Sie, um offline zu lesen
CS221A Data Structures &
Algorithms
Stacks
 Stack
 Stack Operations
 Linked List Implementation of a Stack.
 Stack Applications
Stack
 An Ordered list in which only two operations are
permissible:
 Insertion
 Deletion
 A List (ADT) with restriction that insertions and
deletions can be performed at only one position i.e. the
end of the list called top.
 Items are stored and retrieved in a last-in, first –out
(LIFO) manner.
Stack
 Fundamental operations on a stack are Push, which is
equivalent to insert & Pop which is equivalent to deletion.
Push (S, A)
top
Stack
 Fundamental operations on a stack are Push, which is
equivalent to insert & Pop which is equivalent to deletion.
Push (S, A)
Push (S, B)
top
Stack
 Fundamental operations on a stack are Push, which is
equivalent to insert & Pop which is equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
top
Stack
 Fundamental operations on a stack are Push, which is
equivalent to insert & Pop which is equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
Push (S, D) top
Stack
 Fundamental operations on a stack are Push, which is
equivalent to insert & Pop which is equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
Push (S, D)
Pop ()
top
Stack
 Fundamental operations on a stack are Push, which is
equivalent to insert & Pop which is equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
Push (S, D)
Pop ()
Pop ()
top
Stack
 Fundamental operations on a stack are Push, which is
equivalent to insert & Pop which is equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
Push (S, D)
Pop ()
Pop ()
Pop ()
top
Stack
 Fundamental operations on a stack are Push, which is
equivalent to insert & Pop which is equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
Push (S, D)
Pop ()
Pop ()
Pop ()
Pop ()
top
Stack
 Push by inserting at the front of the list.
 Pop by deleting the element at the front of the list.
 Top examines the element at the front of the list and
returns its value.
Stack Structure
 struct node
 {
 ElementType Element;
 struct node* prev;
 }
Stack Operations
 Push Algorithm
 Push(value, top)
 {
 PtrToMyNewNode = CreateMyNewNode(sizeof(node))
 PtrToMyNewNode  Element = value
 PtrToMyNewNode  prev = top
 top = PtrToMyNewNode
 }
Stack Operations
 void push(ElementType x, Stack top)
 {
 struct node *PtrToNode =
malloc(sizeof(struct node));
 PtrToNode  Element = x;
 PtrToNode  prev = top;
 top = PtrToNode;
 }
Stack Operations
 Pop Algorithm
 Pop(top)
 {
 tempPointer = top
 top = top  prev
 return tempPointer
 }
Stack Operations
 struct node* pop( Stack top)
 {
 struct node* tempPointer = top;
 top = top  prev;
 return tempPointer;
 }
Stack Operations (Book Imp.)
 Struct Node
 {
 ElementType Element;
 Struct Node *Next;
 }
Stack Operations (Book Imp.)
 struct Node;
 typedef struct Node *PtrToNode;
 typedef PtrToNode Stack; // S
Push Operation (Book Imp.)
S
Push Operation (Book Imp.)
S
PtrToNodeTmpCell = malloc (sizeof(struct Node));
TmpCell  Element = “A”;
TmpCell
Push Operation (Book Imp.)
PtrToNodeTmpCell = malloc (sizeof(struct Node));
TmpCell  Element = “A”;
TmpCell  Next = S  Next;
S  Next = TmpCell;
TmpCell
S
Push Operation (Book Imp.)
PtrToNodeTmpCell = malloc (sizeof(struct Node));
TmpCell  Element = “B”;
S
TmpCell
Push Operation (Book Imp.)
TmpCell
S
PtrToNodeTmpCell = malloc (sizeof(struct Node));
TmpCell  Element = “B”;
TmpCell  Next = S  Next;
Push Operation (Book Imp.)
TmpCell
S
PtrToNodeTmpCell = malloc (sizeof(struct Node));
TmpCell  Element = “B”;
TmpCell  Next = S  Next;
S  Next = TmpCell;
Push Operation (Book Imp.)
 void Push(ElementType X, Stack S)
 {
 PtrToNode TmpCell = malloc(sizeof(struct Node));
 if (TmpCell == NULL)
 {
 FatalError (“Out of Space!”);
 }
 else
 {
 TmpCellElement = X;
 TmpCellNext = SNext;
 SNext = TmpCell;
 }
 }
Stack Operations
 int IsEmpty(Stack S)
 {
 return SNext == NULL;
 }
Stack Operations
 ElementType Top(Stack S)
 {
 if (!IsEmpty(S))
 {
 return SNextElement;
 }
 return 0;
 }
Stack Operations
 void Pop(Stack S)
 {
 PtrToNode FirstCell;
 if (!IsEmpty(S))
 {
 Error(“Empty Stack”);
 }
 else
 {
 FirstCell = SNext;
 SNext = SNextNext;
 Free(FirstCell);
 }
 }
Stack Operations
 void MakeEmpty(Stack S)
 {
 while ( !IsEmpty(S))
 {
 Pop(S);
 }
 }
Array Implementation of Stack
 Associated with each stack is TopOfStack, which is -1 for
an empty stack.
 To push some element X onto the stack.We increment
TopOfStack and then set Stack[TopOfStack] = X.
 To pop we set the return value to Stack[TopOfStack]
and then decrement.
Array Implementation of Stack
 Struct StackRecord
 {
 int Capacity;
 int TopOfStack;
 ElementType *Array;
 }
Array Implementation of Stack
 void Push(ElementType X, Stack S)
 {
 if (IsFull(S))
 {
 Error (“Full Stack”);
 }
 else
 {
 SArray[++STopOfStack] = X;
 }
 }
Array Implementation of Stack
 ElementType TopAndPop(Stack S)
 {
 if (!IsEmpty(S))
 {
 return SArray[STopOfStack--];
 }
 Error(“Empty Stack”);
 return 0;
 }
Array Implementation of Stack
 Stack CreateStack(int MaxElements)
 {
 if (MaxElements < MinStackSize)
 {
 Error (“Stack size is too small”);
 }
 Stack S = malloc(sizeof(StackRecord));
 SArray =
malloc(sizeof(ElementType)*MaxElements);
 SCapacity = MaxElements;
 return S;
 }
Stack Applications
 Balancing Symbols
 Read Characters till EOF
 If Character == opening symbol then Push (Character)
 If Character == closing symbol && !IsEmpty(Stack) then Pop( )
 If Poped Symbol isn't the corresponding opening symbol then
Error( )
 At EOF IsEmpty(Stack) == False then Error( )
Stack Applications
 Postfix Calculators
 Postfix notation is : Operand Operand Operator
 5 4 + , 6 5 3 4 * 4 4 + 8 * + 3 *
 Easiest way to calculate is by using a stack.
 When input == Operand than Push (Number)
 When input == Operator than Pop ( Two Pushed
Numbers) and apply the operator and Push (Result).
 Execute couple of examples:
 6 5 2 3 + 8 * + 3 + * = 288
 5 1 2 + 4 * + 3 − = 14
Stack Applications
 Postfix Calculations
 5 1 2 + 4 * + 3 −
Stack Applications
 Infix to Postfix Conversion
 Operand Operator Operand  Operand Operand
Operator
 5 + 4  5 4 +
Stack Applications
 Infix to Postfix Conversion
 If input = operand : add it to the output.
 Else if input = operator, o1 :
 1) while there is an operator, o2, at the top of the stack, and either o1 is associative
or left-associative, and its precedence is less than or equal to that of o2, or o1 is
right-associative and its precedence is less than that of o2, pop o2 off the stack,
onto the output
 2) push o1 onto the operator stack. Else if the input is a left parenthesis, then push
it onto the stack.
 Else if the input is a right parenthesis, then pop operators off the stack,
onto the output until the token at the top of the stack is a left
parenthesis, at which point it is popped off the stack but not added to
the output queue. If the stack runs out without finding a left parenthesis,
then there are mismatched parentheses.
 When there are no more inputs, pop all the operators, if any, off the
stack, add each to the output as it is popped out and exit. (These must
only be operators; if a left parenthesis is popped, then there are
mismatched parentheses.)
Stack Applications
 Infix to Postfix Conversion
 3+4*2/(1-5)^2  3 4 2 * 1 5 - 2 ^ / +
 a+b*c+(d*e+f)*g  abc*+de*f+g*+
Stack Applications
 Infix to Postfix Conversion
 a+b*c+(d*e+f)*g  abc*+de*f+g*+
Operand “a” is read passed to the output.
Operator “+” is read pushed into the stack.
Operand “b” is read passed to the output.
Stack Applications
 Infix to Postfix Conversion
 a+b*c+(d*e+f)*g  abc*+de*f+g*+
Operator “ * “ is read, top of the stack has lower
Precedence than * , so * is pushed.
Operand “c” is read passed to the output.
Stack Applications
 Infix to Postfix Conversion
 a+b*c+(d*e+f)*g  abc*+de*f+g*+
Operator “+” is read. top of the stack has higher
Precedence than + so * is poped. Other + is also poped
As it has equal precedence as “+”. + is pushed.
Stack Applications
 Infix to Postfix Conversion
 a+b*c+(d*e+f)*g  abc*+de*f+g*+
Operator “(” is read.
Highest Precedence “(“ is pushed.
Operand “d” is read passed to the output..
Stack Applications
 Infix to Postfix Conversion
 a+b*c+(d*e+f)*g  abc*+de*f+g*+
Operator “ * ” is read & pushed.
Stack Applications
 Infix to Postfix Conversion
 a+b*c+(d*e+f)*g  abc*+de*f+g*+
Operator “+” is read.
Operator “*” is pop passed to the output then “+” is
Pushed.
Stack Applications
 Infix to Postfix Conversion
 a+b*c+(d*e+f)*g  abc*+de*f+g*+
Operator “)” is read.
Stack is emptied back to “)”. + is passed to the output
Stack Applications
 Infix to Postfix Conversion
 a+b*c+(d*e+f)*g  abc*+de*f+g*+
Operator “ * ” is read & pushed.
Operand “g” is read and passed to the output.
Stack Applications
 Infix to Postfix Conversion
 a+b*c+(d*e+f)*g  abc*+de*f+g*+
Input is empty so pop the stack and pass the operators
To output.

Weitere ähnliche Inhalte

Was ist angesagt?

Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3
Hariz Mustafa
 
data structure, stack, stack data structure
data structure, stack, stack data structuredata structure, stack, stack data structure
data structure, stack, stack data structure
pcnmtutorials
 

Was ist angesagt? (20)

Stack, queue and hashing
Stack, queue and hashingStack, queue and hashing
Stack, queue and hashing
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
Guava Overview. Part 1 @ Bucharest JUG #1
Guava Overview. Part 1 @ Bucharest JUG #1 Guava Overview. Part 1 @ Bucharest JUG #1
Guava Overview. Part 1 @ Bucharest JUG #1
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 
7 stacksqueues
7 stacksqueues7 stacksqueues
7 stacksqueues
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
Data Structure (Stack)
Data Structure (Stack)Data Structure (Stack)
Data Structure (Stack)
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applications
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Stack project
Stack projectStack project
Stack project
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
Stack & queue
Stack & queueStack & queue
Stack & queue
 
data structure, stack, stack data structure
data structure, stack, stack data structuredata structure, stack, stack data structure
data structure, stack, stack data structure
 

Ähnlich wie Stacks

Stack linked list
Stack linked listStack linked list
Stack linked list
bhargav0077
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
KALPANAC20
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
haaamin01
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
tameemyousaf
 

Ähnlich wie Stacks (20)

Stack linked list
Stack linked listStack linked list
Stack linked list
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Stack
StackStack
Stack
 
stack (1).pptx
stack (1).pptxstack (1).pptx
stack (1).pptx
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
Lecture5
Lecture5Lecture5
Lecture5
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
stack-Intro.pptx
stack-Intro.pptxstack-Intro.pptx
stack-Intro.pptx
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
Stack
StackStack
Stack
 
04 stacks
04 stacks04 stacks
04 stacks
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 
Stacks
StacksStacks
Stacks
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Kürzlich hochgeladen (20)

How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 

Stacks

  • 1. CS221A Data Structures & Algorithms Stacks
  • 2.  Stack  Stack Operations  Linked List Implementation of a Stack.  Stack Applications
  • 3. Stack  An Ordered list in which only two operations are permissible:  Insertion  Deletion  A List (ADT) with restriction that insertions and deletions can be performed at only one position i.e. the end of the list called top.  Items are stored and retrieved in a last-in, first –out (LIFO) manner.
  • 4. Stack  Fundamental operations on a stack are Push, which is equivalent to insert & Pop which is equivalent to deletion. Push (S, A) top
  • 5. Stack  Fundamental operations on a stack are Push, which is equivalent to insert & Pop which is equivalent to deletion. Push (S, A) Push (S, B) top
  • 6. Stack  Fundamental operations on a stack are Push, which is equivalent to insert & Pop which is equivalent to deletion. Push (S, A) Push (S, B) Push (S, C) top
  • 7. Stack  Fundamental operations on a stack are Push, which is equivalent to insert & Pop which is equivalent to deletion. Push (S, A) Push (S, B) Push (S, C) Push (S, D) top
  • 8. Stack  Fundamental operations on a stack are Push, which is equivalent to insert & Pop which is equivalent to deletion. Push (S, A) Push (S, B) Push (S, C) Push (S, D) Pop () top
  • 9. Stack  Fundamental operations on a stack are Push, which is equivalent to insert & Pop which is equivalent to deletion. Push (S, A) Push (S, B) Push (S, C) Push (S, D) Pop () Pop () top
  • 10. Stack  Fundamental operations on a stack are Push, which is equivalent to insert & Pop which is equivalent to deletion. Push (S, A) Push (S, B) Push (S, C) Push (S, D) Pop () Pop () Pop () top
  • 11. Stack  Fundamental operations on a stack are Push, which is equivalent to insert & Pop which is equivalent to deletion. Push (S, A) Push (S, B) Push (S, C) Push (S, D) Pop () Pop () Pop () Pop () top
  • 12. Stack  Push by inserting at the front of the list.  Pop by deleting the element at the front of the list.  Top examines the element at the front of the list and returns its value.
  • 13. Stack Structure  struct node  {  ElementType Element;  struct node* prev;  }
  • 14. Stack Operations  Push Algorithm  Push(value, top)  {  PtrToMyNewNode = CreateMyNewNode(sizeof(node))  PtrToMyNewNode  Element = value  PtrToMyNewNode  prev = top  top = PtrToMyNewNode  }
  • 15. Stack Operations  void push(ElementType x, Stack top)  {  struct node *PtrToNode = malloc(sizeof(struct node));  PtrToNode  Element = x;  PtrToNode  prev = top;  top = PtrToNode;  }
  • 16. Stack Operations  Pop Algorithm  Pop(top)  {  tempPointer = top  top = top  prev  return tempPointer  }
  • 17. Stack Operations  struct node* pop( Stack top)  {  struct node* tempPointer = top;  top = top  prev;  return tempPointer;  }
  • 18. Stack Operations (Book Imp.)  Struct Node  {  ElementType Element;  Struct Node *Next;  }
  • 19. Stack Operations (Book Imp.)  struct Node;  typedef struct Node *PtrToNode;  typedef PtrToNode Stack; // S
  • 21. Push Operation (Book Imp.) S PtrToNodeTmpCell = malloc (sizeof(struct Node)); TmpCell  Element = “A”; TmpCell
  • 22. Push Operation (Book Imp.) PtrToNodeTmpCell = malloc (sizeof(struct Node)); TmpCell  Element = “A”; TmpCell  Next = S  Next; S  Next = TmpCell; TmpCell S
  • 23. Push Operation (Book Imp.) PtrToNodeTmpCell = malloc (sizeof(struct Node)); TmpCell  Element = “B”; S TmpCell
  • 24. Push Operation (Book Imp.) TmpCell S PtrToNodeTmpCell = malloc (sizeof(struct Node)); TmpCell  Element = “B”; TmpCell  Next = S  Next;
  • 25. Push Operation (Book Imp.) TmpCell S PtrToNodeTmpCell = malloc (sizeof(struct Node)); TmpCell  Element = “B”; TmpCell  Next = S  Next; S  Next = TmpCell;
  • 26. Push Operation (Book Imp.)  void Push(ElementType X, Stack S)  {  PtrToNode TmpCell = malloc(sizeof(struct Node));  if (TmpCell == NULL)  {  FatalError (“Out of Space!”);  }  else  {  TmpCellElement = X;  TmpCellNext = SNext;  SNext = TmpCell;  }  }
  • 27. Stack Operations  int IsEmpty(Stack S)  {  return SNext == NULL;  }
  • 28. Stack Operations  ElementType Top(Stack S)  {  if (!IsEmpty(S))  {  return SNextElement;  }  return 0;  }
  • 29. Stack Operations  void Pop(Stack S)  {  PtrToNode FirstCell;  if (!IsEmpty(S))  {  Error(“Empty Stack”);  }  else  {  FirstCell = SNext;  SNext = SNextNext;  Free(FirstCell);  }  }
  • 30. Stack Operations  void MakeEmpty(Stack S)  {  while ( !IsEmpty(S))  {  Pop(S);  }  }
  • 31. Array Implementation of Stack  Associated with each stack is TopOfStack, which is -1 for an empty stack.  To push some element X onto the stack.We increment TopOfStack and then set Stack[TopOfStack] = X.  To pop we set the return value to Stack[TopOfStack] and then decrement.
  • 32. Array Implementation of Stack  Struct StackRecord  {  int Capacity;  int TopOfStack;  ElementType *Array;  }
  • 33. Array Implementation of Stack  void Push(ElementType X, Stack S)  {  if (IsFull(S))  {  Error (“Full Stack”);  }  else  {  SArray[++STopOfStack] = X;  }  }
  • 34. Array Implementation of Stack  ElementType TopAndPop(Stack S)  {  if (!IsEmpty(S))  {  return SArray[STopOfStack--];  }  Error(“Empty Stack”);  return 0;  }
  • 35. Array Implementation of Stack  Stack CreateStack(int MaxElements)  {  if (MaxElements < MinStackSize)  {  Error (“Stack size is too small”);  }  Stack S = malloc(sizeof(StackRecord));  SArray = malloc(sizeof(ElementType)*MaxElements);  SCapacity = MaxElements;  return S;  }
  • 36. Stack Applications  Balancing Symbols  Read Characters till EOF  If Character == opening symbol then Push (Character)  If Character == closing symbol && !IsEmpty(Stack) then Pop( )  If Poped Symbol isn't the corresponding opening symbol then Error( )  At EOF IsEmpty(Stack) == False then Error( )
  • 37. Stack Applications  Postfix Calculators  Postfix notation is : Operand Operand Operator  5 4 + , 6 5 3 4 * 4 4 + 8 * + 3 *  Easiest way to calculate is by using a stack.  When input == Operand than Push (Number)  When input == Operator than Pop ( Two Pushed Numbers) and apply the operator and Push (Result).  Execute couple of examples:  6 5 2 3 + 8 * + 3 + * = 288  5 1 2 + 4 * + 3 − = 14
  • 38. Stack Applications  Postfix Calculations  5 1 2 + 4 * + 3 −
  • 39. Stack Applications  Infix to Postfix Conversion  Operand Operator Operand  Operand Operand Operator  5 + 4  5 4 +
  • 40. Stack Applications  Infix to Postfix Conversion  If input = operand : add it to the output.  Else if input = operator, o1 :  1) while there is an operator, o2, at the top of the stack, and either o1 is associative or left-associative, and its precedence is less than or equal to that of o2, or o1 is right-associative and its precedence is less than that of o2, pop o2 off the stack, onto the output  2) push o1 onto the operator stack. Else if the input is a left parenthesis, then push it onto the stack.  Else if the input is a right parenthesis, then pop operators off the stack, onto the output until the token at the top of the stack is a left parenthesis, at which point it is popped off the stack but not added to the output queue. If the stack runs out without finding a left parenthesis, then there are mismatched parentheses.  When there are no more inputs, pop all the operators, if any, off the stack, add each to the output as it is popped out and exit. (These must only be operators; if a left parenthesis is popped, then there are mismatched parentheses.)
  • 41. Stack Applications  Infix to Postfix Conversion  3+4*2/(1-5)^2  3 4 2 * 1 5 - 2 ^ / +  a+b*c+(d*e+f)*g  abc*+de*f+g*+
  • 42. Stack Applications  Infix to Postfix Conversion  a+b*c+(d*e+f)*g  abc*+de*f+g*+ Operand “a” is read passed to the output. Operator “+” is read pushed into the stack. Operand “b” is read passed to the output.
  • 43. Stack Applications  Infix to Postfix Conversion  a+b*c+(d*e+f)*g  abc*+de*f+g*+ Operator “ * “ is read, top of the stack has lower Precedence than * , so * is pushed. Operand “c” is read passed to the output.
  • 44. Stack Applications  Infix to Postfix Conversion  a+b*c+(d*e+f)*g  abc*+de*f+g*+ Operator “+” is read. top of the stack has higher Precedence than + so * is poped. Other + is also poped As it has equal precedence as “+”. + is pushed.
  • 45. Stack Applications  Infix to Postfix Conversion  a+b*c+(d*e+f)*g  abc*+de*f+g*+ Operator “(” is read. Highest Precedence “(“ is pushed. Operand “d” is read passed to the output..
  • 46. Stack Applications  Infix to Postfix Conversion  a+b*c+(d*e+f)*g  abc*+de*f+g*+ Operator “ * ” is read & pushed.
  • 47. Stack Applications  Infix to Postfix Conversion  a+b*c+(d*e+f)*g  abc*+de*f+g*+ Operator “+” is read. Operator “*” is pop passed to the output then “+” is Pushed.
  • 48. Stack Applications  Infix to Postfix Conversion  a+b*c+(d*e+f)*g  abc*+de*f+g*+ Operator “)” is read. Stack is emptied back to “)”. + is passed to the output
  • 49. Stack Applications  Infix to Postfix Conversion  a+b*c+(d*e+f)*g  abc*+de*f+g*+ Operator “ * ” is read & pushed. Operand “g” is read and passed to the output.
  • 50. Stack Applications  Infix to Postfix Conversion  a+b*c+(d*e+f)*g  abc*+de*f+g*+ Input is empty so pop the stack and pass the operators To output.