Stacks.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

COMPSCI 105 S Principles of Computer Science 13 Stacks.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
CMPT 225 Stacks.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Infix to postfix conversion Process the tokens from a vector infixVect of tokens (strings) of an infix expression one by one When the token is an operand.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Stacks Chapter Chapter Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions Checking for Balanced Parentheses,
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Stack: Linked List Implementation Push and pop at the head of the list New nodes should be inserted at the front of the list, so that they become the top.
More About Stacks: Stack Applications Dan Nguyen CS 146, Spring 2004 Professor Sin-Min Lee.
Chapter 16 Stacks and Queues Saurav Karmakar Spring 2007.
Objectives of these slides:
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
1 Stacks – Chapter 3 A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. Alternatively,
Chapter 4 Stacks Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving. Its called.
Data Structures. The Stack: Definition A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
 STACK STACK  BASIC STACK OPERATIONS BASIC STACK OPERATIONS  PUSH ALGORITHM PUSH ALGORITHM  POP ALGORITHM POP ALGORITHM  EVALUATING A POSTFIX EXPRESSION.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Stacks An Abstract Data Type. Restricted Access Unlike arrays, stacks only allow the top most item to be accessed at any time The interface of a stack.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
CHP-3 STACKS.
Stacks & Queues. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy to use.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
Lecture - 6(Stacks) On Data structures. Prepared by, Jesmin Akhter, Lecturer, IIT,JU Lecture Outline What is a Stack? Array implementation of stacks Operations.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Chapter 4 Stacks
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
Data Structures Using C++ 2E
Stacks Chapter 6.
MEMORY REPRESENTATION OF STACKS
CC 215 Data Structures Stack ADT
Stack and Queue APURBO DATTA.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Stacks Stack: restricted variant of list
Data Structures – Week #3
Algorithms and Data Structures
Visit for more Learning Resources
PART II STACK APPLICATIONS
Stack.
Introduction to Data Structures
Stacks Chapter 5 Adapted from Pearson Education, Inc.
More About Stacks: Stack Applications
Stack and Queues Stack implementation using Array
Stacks Chapter 6 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Stacks and Queues 1.
Stacks Data structure Elements added, removed from one end only
Topic 15 Implementing and Using Stacks
Stacks CS-240 Dick Steflik.
Stack.
Data Structures – Week #3
More About Stacks: Stack Applications
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Presented by : Aman Gupta PGT CS KV No.1, Narimedu, Madurai
5.3 Implementing a Stack Chapter 5 – The Stack.
Presentation transcript:

Stacks

Stack A stack is a data structure that works on the principle of Last In First Out (LIFO). So last item put on the stack is the first item that can be taken off, like a physical stack of books/plates. In stack new elements are added to and removed from the top of the structure.

Two Implementations of Stack As Vector (Array) Storing the items contiguously . As List Storing items noncontiguously.

Operations of Stack IsEmpty: return true if stack is empty, return false otherwise IsFull: return true if stack is full, return false otherwise Top: return the element at the top of stack Push: add an element to the top of stack Pop: delete the element at the top of stack DisplayStack: print all the data in the stack

Array Implementation To use an array to implement a stack, you need both the array itself and an integer The integer tells you either: Which location is currently the top of the stack, or How many elements are in the stack for an empty stack, set ToS to -1

Push (1)   Increment ToS by 1. (2)   Set Stack[ToS] = X Pop (1)   Set return value to Stack[ToS] (2)   Decrement ToS by 1 These operations are performed in very fast constant time

How stack works 5 7 5 5 Empty stack push(5) push(7) pop() tos=1 tos=0

Create Stack Create an empty stack by setting Top of the stack to -1 { TOS=-1; }

Push Stack void Push(int x); Push an element onto the stack If the stack is full, print the error information. Note top always represents the index of the top element. First increment top, then push on to stack. Void push(int x) { if(isFull()) printf(" Stack overflow"); else TOS++; Stack[TOS]=x; }

Pop Stack int Pop() Pop means return the element at the top of the stack If the stack is empty, print the error information. Don’t forgot to decrement TOS. pop() { if (isEmpty()) printf( "Stack Underflow"); else return(Stack[TOS--]); }

Stack Top int Top(int Stack[]) Return the top element of the stack Unlike Pop, this function does not remove the top element int Top(int Stack[ ]) { if (isEmpty()) { printf("\n Stack is empty"); return; } return Stack[TOS];

Printing all the elements void DisplayStack() Print all the elements Void displayStack() { int i; printf("Top -->"); for(i=TOS;i>=0;i--) printf("\t \t%d \n" ,Stack[i]); }

Linked List Implementation Advantage of the linked list : using only one pointer per item at a time. Disadvantage of contiguous vector implementation : using excess space equal to the number of vacant array items .

Linked List Implementation of Stack The stack can be implemented as a linked list in which the top of the stack is represented by the first item in the list. topOfStack

Linked List Implementation of Stack Each stack item stores element value pointer to next element

Node Structure of the Stack typedef struct node{ int item; struct node *next; }Node; //Create Empty stack Node *Stack=NULL;

Push operation void Push(int x) { Node *top; top=(Node *)malloc(sizeof(Node)); top->item=x; top->next=Stack; Stack=top; }

List Stack Example Stack 6 push(6); void Push(int x) { Node *top; top=(Node *)malloc(sizeof(Node)); top->item=x; top->next=Stack; Stack=top; } Stack 6 top

List Stack Example push(6); push(1); Stack 1 6

List Stack Example push(6); push(1); push(7); 7 stack 1 6

List Stack Example push(6); push(1); push(7); push(8); 8 7 stack 1 6

Pop Stack //Pop from a stack int Pop(Node *Stack) {Node *temp; int i; if (IsEmpty(Stack)) printf("Stack empty"); else { temp=Stack; i=temp->item; Stack=Stack->next; free(temp); return i; }

List Stack Example 8 7 stack 1 6 push(6); push(1); push(7); push(8); pop(); 8 7 stack 1 6

List Stack Example 7 stack 1 6 push(6); push(1); push(7); push(8); pop(); 7 stack 1 6

IsEmpty - to Check whether the stack is empty int IsEmpty(Node *Stack) { if(Stack == NULL) return 1; }

Retrieve the Top element of the stack int Top(Node *S) { if (!IsEmpty(S)) return (S->item); printf("Empty stack"); return 0; }

List Stack Example 8 7 stack 1 6 push(6); push(1); push(7); push(8); Top() pop(); Top(); 8 7 stack 1 6 Top element retrieved is 8 Top element retrieved is 7

Display the stack void displayStack(Node *Stack) { Node *temp; temp=Stack; printf("Top--->"); while(temp!=NULL) printf("\t\t%d\n",temp->item); temp=temp->next; }

Application of Stack Recognizing palindromes Checking balanced expressions Evaluating algebraic expressions is easier. Searching networks, traversing trees (keeping a track where we are).

Stack Applications Converting Decimal to Binary: Consider the following pseudocode Read (number) Loop (number > 0) 1) digit = number modulo 2 2) print (digit) 3) number = number / 2 // from Data Structures by Gilbert and Forouzan The problem with this code is that it will print the binary number backwards. (ex: 19 becomes 11001000 instead of 00010011. ) To remedy this problem, instead of printing the digit right away, we can push it onto the stack. Then after the number is done being converted, we pop the digit out of the stack and print it.

Simple Applications of the ADT Stack: Checking for Balanced Braces A stack can be used to verify whether a program contains balanced braces An example of balanced braces abc{defg{ijk}{l{mn}}op}qr An example of unbalanced braces abc{def}}{ghij{kl}m abc{def}{ghij{kl}m

Checking for Balanced Braces Requirements for balanced braces Each time you encounter a “}”, it matches an already encountered “{” When you reach the end of the string, you have matched each “{”

Checking for Balanced Braces Figure 7-3 Traces of the algorithm that checks for balanced braces

Infix to Postfix Conversion Scan the Infix string from left to right. Initialise an empty stack. If the scannned character is an operand, add it to the Postfix string. If the scanned character is an operator and if the stack is empty Push the character to stack. If the scanned character is an Operator and the stack is not empty, compare the precedence of the character with the element on top of the stack (topStack). If topStack has higher precedence over the scanned character Pop the stack else Push the scanned character to stack. Repeat this step as long as stack is not empty and topStack has precedence over the character. Repeat this step till all the characters are scanned. (After all characters are scanned, we have to add any character that the stack may have to the Postfix string.) If stack is not empty add topStack to Postfix string and Pop the stack. Repeat this step as long as stack is not empty. Return the Postfix string.

Example : String a+b*c-d              STACK                      PostfixString

Infix to Postfix Example A + B * C - D / E Infix Stack(bot->top) Postfix a) A + B * C - D / E b) + B * C - D / E A c) B * C - D / E + A d) * C - D / E + A B e) C - D / E + * A B f) - D / E + * A B C g) D / E - A B C * + h) / E - A B C * + D i) E - / A B C * + D j) - / A B C * + D E k) A B C * + D E / -

Infix to Postfix Example #2 A * B - ( C + D ) + E Infix Stack(bot->top) Postfix A * B - ( C - D ) + E empty empty * B - ( C + D ) + E empty A B - ( C + D ) + E * A - ( C + D ) + E * A B - ( C + D ) + E empty A B * ( C + D ) + E - A B * C + D ) + E - ( A B * + D ) + E - ( A B * C D ) + E - ( + A B * C ) + E - ( + A B * C D + E - A B * C D + + E empty A B * C D + - E + A B * C D + - + A B * C D + - E empty A B * C D + - E +

Transform postfix to infix: a)Push each operand in the stack until an operation is encountered. b)Pop two operands and wrap them around their operation. c) repeat until done. Transform Prefix to infix: Same as above, but we start parsing from right to left. Example: + B * C D

Evaluating Postfix Expressions A postfix (reverse Polish logic) calculator Requires you to enter postfix expressions Example: 2 3 4 + * When an operand is entered, the calculator Pushes it onto a stack When an operator is entered, the calculator Applies it to the top two operands of the stack Pops the operands from the stack Pushes the result of the operation on the stack

Evaluating Postfix Expressions Figure 7-8 The action of a postfix calculator when evaluating the expression 2 * (3 + 4)

Postfix Expression Evaluation for each character C in a given string { if C is an operand push C onto stack; else // C is an operator pop item from stack, and store in Opr2; pop item from stack, and store in Opr1; result = Opr1 C Opr2, using C as an operator; push result onto stack; }

Application of Stacks – Contd..