Application of Stack (Backtracking)

Size: px
Start display at page:

Download "Application of Stack (Backtracking)"

Transcription

1 Application of Stack (Backtracking) Think of a labyrinth or maze How do you find a way from an entrance to an exit? Once you reach a dead end, you must backtrack. But backtrack to where? to the previous choice point.

2 Application: 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

3 Application: A Search Problem Beginning at the origin city, the algorithm will try every possible sequence of flights until either it finds a sequence that gets to the destination city. P is origin city; Z is destination city A Flight Map

4 Stacks BLG221E

5 Introduction to the Stack A stack is a data structure that stores and retrieves items in a last-in-first-out (LIFO) manner. 1st element of stack The first element that is pushed on a stack is the last one to be removed.

6 Stack Push Pop the operation to place a new item at the top of the stack the operation to remove the item from the top of the stack

7 Stack C R X A push(m) M C R X A item = pop() item = M C R X A Push: the operation to place a new item at the top of the stack Pop: the operation to remove the item from the top of the stack

8 Stack Operations Create an empty stack Destroy a stack push pop Determine whether a stack is empty Add a new item -- push top Remove the item that was added most recently -- pop Retrieve the item that was added most recently Stack

9 Applications of Stacks Computer systems use stacks during a program s execution to store function return addresses, local variables, etc. Some calculators use stacks for performing mathematical operations. The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter - and then pop letters from the stack. Another application is an "undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack.

10 Application of Stack (Backtracking) Think of a labyrinth or maze How do you find a way from an entrance to an exit? Once you reach a dead end, you must backtrack. But backtrack to where? to the previous choice point. Therefore, at each choice point you store on a stack all possible choices. Then backtracking simply means popping a next choice from the stack.

11 Stack Computer systems use stacks during a program s execution to store function return addresses, local variables, etc. When a function is called, a frame containing local variables and return adress is pushed on the stack When a function returns, its frame is popped from the stack and control is passed to the method on top of the stack main() { int i = 5; foo(i); } foo(int j) { int k; k = j+1; bar(k); } bar(int m) { } bar m = 6 foo j = 5 k = 6 main i = 5 Run-time Stack

12 Example: Factorial function int fact(int n) { if (n == 0) return (1); else return (n * fact(n-1)); }

13 Tracing the call fact (N=3) When a function returns, its frame is popped from the stack and control is passed to the item on top of the stack N = 0 if (N==0) true return (1) N = 1 N = 1 if (N==0) false if (N==0) false N = 3 if (N==0) false return (3*fact(2)) After original call N = 2 if (N==0) false return (2*fact(1)) N = 3 if (N==0) false return (3*fact(2)) After 1 st call return (1*fact(0)) N = 2 if (N==0) false return (2*fact(1)) N = 3 if (N==0) false return (3*fact(2)) After 2 nd call return (1*fact(0)) N = 2 if (N==0) false return (2*fact(1)) N = 3 if (N==0) false return (3*fact(2)) After 3rd call

14 Tracing the call fact (3) When a function returns, its frame is popped from the stack and control is passed to the item on top of the stack N = 1 if (N==0) false return (1* 1) N = 2 if (N==0) false return (2*fact(1)) N = 2 if (N==0) false return (2* 1) N = 3 N = 3 N = 3 if (N==0) false if (N==0) false if (N==0) false return (3*fact(2)) After return from 3rd call return (3*fact(2)) After return from 2nd call return (3* 2) After return from 1st call return 6

15 Application: 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 When the algortihm encounters open braces push operation is implemented. Otherwise pop operation is implemented.

16 Application: A Search Problem Beginning at the origin city, the algorithm will try every possible sequence of flights until either it finds a sequence that gets to the destination city. P is origin city; Z is destination city A Flight Map

17 Calculating Arithmetic Expression Evaluation of arithmetic expressions ((A/(B*C))+(D*E))-(A*C) operands: A,B,C,D,E operators: /, *, +,-, * Each operation has a certain precedence. The use of parentheses affects the result. Using parentheses, different results could be obtained.

18 Application: Algebraic Expressions To evaluate an infix expression Convert the infix expression to postfix form Evaluate the postfix expression Infix Expression Postfix Expression * * + 5 * * * ( ) * 4 - While generating code, compilers first convert the given expression to a representation called postfix. This postfix expression is then processed using the stack structure. In this representation (postfix), the operands are written before the operators (A B +).

19 Calculating Postfix Expression Infix: (3 + 2) * 10 Postfix: * Scan the postfix expression from left to right : 1) If an operand found, then push it into stack. 2) If an operator found, pop two operands from the stack. 3) Perform the arithmetic operator, then push the result into the stack.

20 If an operand found push it into stack Postfix expression: If an operator found, pop two operands from the stack * Empty stack

21 If an operand found push it into stack Postfix expression: If an operator found, pop two operands from the stack * Stack Push(3)

22 If an operand found push it into stack Postfix expression: If an operator found, pop two operands from the stack * Stack Push(2)

23 If an operand found push it into stack Postfix expression: If an operator found, pop two operands from the stack * Stack + operator found. Pop two operands from stack

24 If an operand found push it into stack Postfix expression: If an operator found, pop two operands from the stack * Stack poped 0 3 poped

25 If an operand found push it into stack Postfix expression: * Stack If an operator found, pop two operands from the stack. Perform the arithmetic operator, then push the result into the stack. Push the result of + operator into stack = Push(5)

26 If an operand found push it into stack Postfix expression: * Stack If an operator found, pop two operands from the stack. Perform the arithmetic operator, then push the result into the stack. Push(10)

27 If an operand found push it into stack Postfix expression: * Stack If an operator found, pop two operands from the stack. Perform the arithmetic operator, then push the result into the stack. * operator found. Pop two operands from stack

28 If an operand found push it into stack Postfix expression: * Stack If an operator found, pop two operands from the stack. Perform the arithmetic operator, then push the result into the stack poped 0 5 poped

29 If an operand found push it into stack Postfix expression: * Stack If an operator found, pop two operands from the stack. Perform the arithmetic operator, then push the result into the stack. Push the result of * operator into stack *5= Push(50)

30 Postfix expression: * Stack End of expression. Pop the final result from stack poped

31 Static and Dynamic Stacks Static Stacks Fixed size Can be implemented with an array Dynamic Stacks Grow in size as needed Can be implemented with a linked list

32 Array implementation of stacks To implement a stack, items are inserted and removed at the same end (called the top). To use an array to implement as a stack, you need both the array itself and an integer variable. The integer tells you either: Which location is currently the top of the stack, or How many elements are in the stack

33 Array implementation of stacks stk: top = 3 or count=4 The bottom of the stack is at location top=0, count =1 Empty stack is represented by top = -1 or count = 0 stk: top = -1 or count=0

34 Pushing stk: To add (push) an element: top = 3 or count=4 Increment top and store the element in stk[top] stk: top = 4 or count=5

35 Popping stk: To remove (pop) an element: top = 3 or count=4 Get the element from stk[top] and decrement [top] stk: top = 2 or count = 3

36 After popping stk: top = 2 or count = 3 When you pop an element, do you leave the deleted element sitting in the array? The surprising answer is, it depends If this is an array of primitives, or if you are programming in C or C++, then doing anything more is just a waste of time If you are programming in Java, and the array contains objects, you should set the deleted array element to null Why? To allow it to be garbage collected!

37 Stack definition #define SIZE 50 int stk[size]; int top=-1; void init_stack() { // Empty stack is represented by top = -1 } top=-1;

38 Push and Pop operations void push( int n ) { if( top==size-1) printf("\nstack is full"); else stk[++top]= n; } int pop( ) { if(top== -1) { printf("\nstack is empty"); return -1; } else return stk[top--]; }

39 Display all elements of stack void display( ) { int i; if(top== -1) printf("\nstack is empty."); else { printf("\nelements are : \n"); for(i=0; i<=top; i++) printf("%5d ",stk[i]); } }

40 Check int isempty( ) { if ( top== -1 ) return 1; else return 0; } int peek( ) { return stk[top]; }

41 Array implementation of stacks #include<stdio.h> #include<conio.h> #include <stdlib.h> #define SIZE 50 int stack[size]; int top; void init_stack() { top=-1; } void push( int n ) { if( top==size-1) printf("\nstack is full"); else stack[++top]= n; } int pop( ) { if(top== -1) { printf("\nstack is empty"); return -1; } else return stack[top--]; } void display( ) { int i; if(top== -1) printf("\nstack is empty."); else { printf("\nelements are : \n"); for(i=0;i<=top;i++) printf("%5d ",stack[i]); } } int isempty( ) { if ( top== -1 ) return 1; else return 0; } int peek( ){ return stack[top]; }

42 Array implementation of stacks(cont.) switch(choice) { case 1:printf("\nEnter the element to push : "); int main() { scanf("%d",&item); int choice,item; push(item); break; init_stack(); case 2:item = pop(); printf("\nelement poped : %d",item); do printf("\npress a key to continue..."); { getche(); break; printf("\n\tmenu\n\t1.push.\n\t2.pop."); case 3:item = peek(); printf("\nelement at top : %d",item); printf("\n\t3.peek.\n\t4.display.\n\t5.exit.\n"); printf("\npress a key to continue..."); printf("\nyour Choice: "); getche(); break; scanf("%d",&choice); case 4:display(); printf("\npress a key to continue..."); getche(); break; case 5:exit(0); } } while(1); } // end of main

43 Sharing space Of course, the bottom of the stack could be at the other end stk: top = 6 or count = 4 Sometimes this is done to allow two stacks to share the same storage area stks: topstk1 = 2 topstk2 = 6

44 Dynamic Stacks Grow in size as needed Can be implemented with a linked list Bottom of stack Top of stack

45 Empty stack head

46 Push(50) head 50

47 Push(30) head Bottom of stack 30 50

48 Push(70) head Bottom of stack

49 Pop() head 70 poped Bottom of stack 30 50

50 Pop() head 30 poped 50

51 Pop() head 50 poped

52 Stack definition struct s_node { int data; struct s_node *link; } *stack=null; stack

53 Push operation //Pushing element in to stack void push(int j) { struct s_node *m; m=new struct s_node ; m->data= j ; m->link=stack; stack=m; return; } Top of stack Bottom of stack Stack Pointer a b c stack = m; m->link = stack; m=new struct s_node ;

54 Pop operations //Popping element from stack int pop( ) { struct s_node *temp=null; if(stack==null) { printf("\nstack is Empty."); getch(); } else { int i=stack->data; temp = stack ; stack=stack->link; delete temp; return (i); } } Top of stack

55 Display all elements of stack //Displaying Stack void display() { struct s_node *temp=stack; while(temp!=null) { printf("%d\t", temp->data); temp=temp->link; } }

56 Linked List implementation of stacks #include<stdio.h> #include<conio.h> #include <stdlib.h> struct s_node { int data; struct s_node *link; } *stack=null; //Pushing element in to stack void push(int j) { struct s_node *m; m=new struct s_node ; m->data= j ; m->link=stack; stack=m; return; } //Popping element from stack int pop( ) { struct s_node *temp=null; if(stack==null) { printf("\nstack is Empty."); getch(); } else { int i=stack->data; temp = stack ; stack=stack->link; delete temp; return (i); } } //Displaying Stack void display() { struct s_node *temp=stack; while(temp!=null) { printf("%d\t",temp->data); temp=temp->link; } } //Calling in main() int main() { int choice,num,i; while(1) { printf("\n\t MENU\n1. Push\n2. Pop\n"); printf("\n3. Elements in Stack\n4. Exit\n"); } } printf("\n\tenter your choice: "); scanf("%d",&choice); switch(choice) { case 1: printf("\nelement to be pushed:"); scanf("%d",&num); push(num); break; case 2: num=pop(); printf("\nelement popped: %d ",num); getch(); break; case 3: printf("\nelements present in stack : " ); display();getch(); break; case 4: exit(1); default: printf("\ninvalid Choice\n"); break; }

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified.

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified. The Stack ADT Stacks Set of objects in which the location an item is inserted and deleted is prespecified Stacks! Insert in order! Delete most recent item inserted! LIFO - last in, first out Stacks 2 The

More information

STACKS 3.1 INTRODUCTION 3.2 DEFINITION

STACKS 3.1 INTRODUCTION 3.2 DEFINITION STACKS 3 3.1 INTRODUCTION A stack is a linear data structure. It is very useful in many applications of computer science. It is a list in which all insertions and deletions are made at one end, called

More information

CSE 214 Computer Science II Stack

CSE 214 Computer Science II Stack CSE 214 Computer Science II Stack Spring 2018 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/ Random and Sequential Access Random

More information

Stacks CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008

Stacks CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008 Chapter 7 s CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008 The Abstract Data Type: Specifications of an abstract data type for a particular problem Can emerge during the design of the

More information

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1 Data Structure using C++ Lecture 04 Reading Material Data Structures and algorithm analysis in C++ Chapter. 3 3.1, 3.2, 3.2.1 Summary Stack Operations on a stack Representing stacks Converting an expression

More information

Stack Abstract Data Type

Stack Abstract Data Type Stacks Chapter 5 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty To understand how Java implements a stack To learn how to implement a

More information

Lecture Data Structure Stack

Lecture Data Structure Stack Lecture Data Structure Stack 1.A stack :-is an abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example a deck of cards

More information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3 Linear and Non-Linear Data Structures Linear data structure: Linear data structures are those data structure in which data items are arranged in a linear sequence by physically or logically or both the

More information

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi Data Structures & Algorithm Analysis Lec(3) Stacks Lecturer: Souad Alonazi 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

More information

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011 Stacks (5.1) CSE 2011 Winter 2011 26 January 2011 1 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data Error

More information

Linked List in Data Structure. By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra

Linked List in Data Structure. By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra Linked List in Data Structure By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra Linked List Like arrays, Linked List is a linear data

More information

DEEPIKA KAMBOJ UNIT 2. What is Stack?

DEEPIKA KAMBOJ UNIT 2. What is Stack? What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you

More information

Stacks. Access to other items in the stack is not allowed A LIFO (Last In First Out) data structure

Stacks. Access to other items in the stack is not allowed A LIFO (Last In First Out) data structure CMPT 225 Stacks Stacks A stack is a data structure that only allows items to be inserted and removed at one end We call this end the top of the stack The other end is called the bottom Access to other

More information

Prepared By:- Dinesh Sharma Asstt. Professor, CSE & IT Deptt. ITM Gurgaon

Prepared By:- Dinesh Sharma Asstt. Professor, CSE & IT Deptt. ITM Gurgaon Data Structures &Al Algorithms Prepared By:- Dinesh Sharma Asstt. Professor, CSE & IT Deptt. ITM Gurgaon What is Data Structure Data Structure is a logical relationship existing between individual elements

More information

March 13/2003 Jayakanth Srinivasan,

March 13/2003 Jayakanth Srinivasan, Statement Effort MergeSort(A, lower_bound, upper_bound) begin T(n) if (lower_bound < upper_bound) Θ(1) mid = (lower_bound + upper_bound)/ 2 Θ(1) MergeSort(A, lower_bound, mid) T(n/2) MergeSort(A, mid+1,

More information

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science IT 4043 Data Structures and Algorithms Budditha Hettige Department of Computer Science 1 Syllabus Introduction to DSA Abstract Data Types List Operation Using Arrays Stacks Queues Recursion Link List Sorting

More information

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider:

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider: Linear, time-ordered structures CS00: Stacks n Prichard Ch 7 n Data structures that reflect a temporal relationship order of removal based on order of insertion n We will consider: first come,first serve

More information

UNIT-2 Stack & Queue

UNIT-2 Stack & Queue UNIT-2 Stack & Queue 59 13. Stack A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example a deck of cards

More information

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved Stacks Chapter 5 Copyright 2012 by Pearson Education, Inc. All rights reserved Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions A Problem Solved: Checking for Balanced

More information

UNIT 2: STACK & RECURSION Programs demonstrated in class. Tojo Mathew Asst. Professor CSE Dept., NIE Mysuru.

UNIT 2: STACK & RECURSION Programs demonstrated in class. Tojo Mathew Asst. Professor CSE Dept., NIE Mysuru. UNIT 2: STACK & RECURSION Programs demonstrated in class. Tojo Mathew Asst. Professor CSE Dept., NIE Mysuru. Table of Contents 1. C Program to Check for balanced parenthesis by using Stacks...3 2. Program

More information

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in themodel answer scheme. 2) The model answer and the answer written by candidate may

More information

Stacks. Revised based on textbook author s notes.

Stacks. Revised based on textbook author s notes. Stacks Revised based on textbook author s notes. Stacks A restricted access container that stores a linear collection. Very common for solving problems in computer science. Provides a last-in first-out

More information

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5 What is Stack? Stack 1. Stack is LIFO Structure [ Last in First Out ] 2. Stack is Ordered List of Elements of Same Type. 3. Stack is Linear List 4. In Stack all Operations such as Insertion and Deletion

More information

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

CS 171: Introduction to Computer Science II. Stacks. Li Xiong CS 171: Introduction to Computer Science II Stacks Li Xiong Today Stacks operations and implementations Applications using stacks Application 1: Reverse a list of integers Application 2: Delimiter matching

More information

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack. STACK Stack ADT 2 A stack is an abstract data type based on the list data model All operations are performed at one end of the list called the top of the stack (TOS) LIFO (for last-in first-out) list is

More information

1. Stack Implementation Using 1D Array

1. Stack Implementation Using 1D Array Lecture 5 Stacks 1 Lecture Content 1. Stack Implementation Using 1D Array 2. Stack Implementation Using Singly Linked List 3. Applications of Stack 3.1 Infix and Postfix Arithmetic Expressions 3.2 Evaluate

More information

Write a C program to add two Complex numbers using functions illustrating-

Write a C program to add two Complex numbers using functions illustrating- Scheme of valuvation Date : 29/8/2017 Marks: 40 Subject & Code : Data Structures and Applications (15CS33) Class : III A&B Name of Faculty : Ms. Saritha Time : 8:30 am to 10 am NOTE: ANSWER All FIVE QUESTIONS

More information

MODULE V: POINTERS & PREPROCESSORS

MODULE V: POINTERS & PREPROCESSORS MODULE V: POINTERS & PREPROCESSORS INTRODUCTION As you know, every variable is a memory-location and every memory-location has its address defined which can be accessed using ampersand(&) operator, which

More information

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004) COMP250: Stacks Jérôme Waldispühl School of Computer Science McGill University Based on slides from (Goodrich & Tamassia, 2004) 2004 Goodrich, Tamassia The Stack ADT A Stack ADT is a list that allows only

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

Outline and Reading. The Stack ADT ( 2.1.1) Applications of Stacks ( 2.1.1) Array-based implementation ( 2.1.1) Growable array-based stack ( 1.

Outline and Reading. The Stack ADT ( 2.1.1) Applications of Stacks ( 2.1.1) Array-based implementation ( 2.1.1) Growable array-based stack ( 1. Stacks Outline and Reading The Stack ADT ( 2.1.1) Applications of Stacks ( 2.1.1) Array-based implementation ( 2.1.1) Growable array-based stack ( 1.5) Stacks 2 Abstract Data Types (ADTs) An abstract data

More information

Associate Professor Dr. Raed Ibraheem Hamed

Associate Professor Dr. Raed Ibraheem Hamed Associate Professor Dr. Raed Ibraheem Hamed University of Human Development, College of Science and Technology Computer Science Department 2015 2016 1 What this Lecture is about: Stack Structure Stack

More information

POLYNOMIAL ADDITION. AIM:- To write a C program to represent a polynomial as a linked list and write functions for polynomial addition.

POLYNOMIAL ADDITION. AIM:- To write a C program to represent a polynomial as a linked list and write functions for polynomial addition. POLYNOMIAL ADDITION AIM:- To write a C program to represent a polynomial as a linked list and write functions for polynomial addition. ALGORITHM:- 1. Start the program 2. Get the coefficients and powers

More information

Chapter 2. Stack & Queues. M hiwa ahmad aziz

Chapter 2. Stack & Queues.   M hiwa ahmad aziz . Chapter 2 Stack & Queues www.raparinweb.com M hiwa ahmad aziz 1 Stack A stack structure with a series of data elements that Allows access to only the last item inserted. An item is inserted or removed

More information

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S Stacks Stacks & Queues A linear sequence, or list, is an ordered collection of elements: S = (s 1, s 2,..., s n ) Stacks and queues are finite linear sequences. A Stack is a LIFO (Last In First Out) list.

More information

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Computer Science and Engineering

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Computer Science and Engineering USN 1 P E PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Computer Science and Engineering SOLUTION FOR INTERNAL ASSESSMENT TEST 2 Date : 6/10/2017 Marks:

More information

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows: STACKS A stack is a linear data structure for collection of items, with the restriction that items can be added one at a time and can only be removed in the reverse order in which they were added. The

More information

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved Stacks Chapter 5 Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions A Problem Solved: Checking for Balanced Delimiters in an Infix Algebraic Expression A Problem Solved:

More information

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016 Stacks Gaddis 18.1, 18.3 Molly A. O'Neil CS 2308 :: Spring 2016 The Stack ADT A stack is an abstract data type that stores a collection of elements of the same type The elements of a stack are accessed

More information

Write a program to implement stack or any other data structure in Java ASSIGNMENT NO 15

Write a program to implement stack or any other data structure in Java ASSIGNMENT NO 15 Write a program to implement stack or any other data structure in Java ASSIGNMENT NO 15 Title: Demonstrate implementation of data structure in Java Objectives: To learn implementation of data structure

More information

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1 Some Applications of Stack Spring Semester 2007 Programming and Data Structure 1 Arithmetic Expressions Polish Notation Spring Semester 2007 Programming and Data Structure 2 What is Polish Notation? Conventionally,

More information

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) WINTER 16 EXAMINATION Model Answer Subject Code:

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) WINTER 16 EXAMINATION Model Answer Subject Code: Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The model answer and the answer written by candidate

More information

Data Structures Week #3. Stacks

Data Structures Week #3. Stacks Data Structures Week #3 Stacks Outline Stacks Operations on Stacks Array Implementation of Stacks Linked List Implementation of Stacks Stack Applications October 5, 2015 Borahan Tümer, Ph.D. 2 Stacks (Yığınlar)

More information

NCS 301 DATA STRUCTURE USING C

NCS 301 DATA STRUCTURE USING C NCS Data Structure Using C -8- NCS DATA STRUCTURE USING C Unit- Part- Stack Hammad Mashkoor Lari Assistant Professor Allenhouse Institute of Technology www.ncsds.wordpress.com Introduction Stack is a non

More information

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO) Outline stacks stack ADT method signatures array stack implementation linked stack implementation stack applications infix, prefix, and postfix expressions 1 Stacks stacks of dishes or trays in a cafeteria

More information

/*Addition of two polynomials*/ #include<stdio.h> #include<malloc.h> #include<conio.h> struct link { int coeff; int pow; struct link *next; }; struct

/*Addition of two polynomials*/ #include<stdio.h> #include<malloc.h> #include<conio.h> struct link { int coeff; int pow; struct link *next; }; struct /*Addition of two polynomials*/ #include #include #include struct link int coeff; int pow; struct link *next; ; struct link *poly1=null,*poly2=null,*poly=null; void create(struct

More information

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed stack method of expression evaluation in 1955. Topic 15 Implementing and Using "stack n. The set of things a person has to do in the future. "I haven't done it yet because every time I pop my stack something new gets pushed." If you are interrupted

More information

Stacks. Manolis Koubarakis. Data Structures and Programming Techniques

Stacks. Manolis Koubarakis. Data Structures and Programming Techniques Stacks Manolis Koubarakis 1 Stacks and Queues Linear data structures are collections of components arranged in a straight line. If we restrict the growth of a linear data structure so that new components

More information

Linear Data Structure

Linear Data Structure Linear Data Structure Definition A data structure is said to be linear if its elements form a sequence or a linear list. Examples: Array Linked List Stacks Queues Operations on linear Data Structures Traversal

More information

Module III. Linear Data Structures and their Linked Storage Representation

Module III. Linear Data Structures and their Linked Storage Representation Module III Linear Data Structures and their Linked Storage Representation 3.1 Linked List Linked list is the collection of inter connected nodes with a head node representing the first node and a tail

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE TED (10)-3071 Reg. No.. (REVISION-2010) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours (Maximum marks: 100)

More information

STACKS AND QUEUES. Problem Solving with Computers-II

STACKS AND QUEUES. Problem Solving with Computers-II STACKS AND QUEUES Problem Solving with Computers-II 2 Stacks container class available in the C++ STL Container class that uses the Last In First Out (LIFO) principle Methods i. push() ii. iii. iv. pop()

More information

Stack and Its Implementation

Stack and Its Implementation Stack and Its Implementation Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale tessema.mengistu@siu.edu Room - 3131 1 Definition of Stack Usage of Stack Outline

More information

DHANALAKSHMI COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES

DHANALAKSHMI COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES DHANALAKSHMI COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES UNIT III LINEAR DATA STRUCTURES PART A 1. What is meant by data

More information

Formal Languages and Automata Theory, SS Project (due Week 14)

Formal Languages and Automata Theory, SS Project (due Week 14) Formal Languages and Automata Theory, SS 2018. Project (due Week 14) 1 Preliminaries The objective is to implement an algorithm for the evaluation of an arithmetic expression. As input, we have a string

More information

An Introduction to Trees

An Introduction to Trees An Introduction to Trees Alice E. Fischer Spring 2017 Alice E. Fischer An Introduction to Trees... 1/34 Spring 2017 1 / 34 Outline 1 Trees the Abstraction Definitions 2 Expression Trees 3 Binary Search

More information

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1 Abstract Data Types Stack January 26, 2018 Cinda Heeren / Geoffrey Tien 1 Abstract data types and data structures An Abstract Data Type (ADT) is: A collection of data Describes what data are stored but

More information

Computer Programming for Engineering Applica4ons. Intro to Programming 10/17/13 ECE 175. The Stack Data Structure. Examples from Real Life

Computer Programming for Engineering Applica4ons. Intro to Programming 10/17/13 ECE 175. The Stack Data Structure. Examples from Real Life Computer Programming for Engineering Applica4ons ECE 175 Intro to Programming The Stack Data Structure Stack: An alloca4on of memory to store data (usually temporary data) Data are inserted, and deleted

More information

Solution for Data Structure

Solution for Data Structure Solution for Data Structure May 2016 INDEX Q1 a 2-3 b 4 c. 4-6 d 7 Q2- a 8-12 b 12-14 Q3 a 15-18 b 18-22 Q4- a 22-35 B..N.A Q5 a 36-38 b N.A Q6- a 39-42 b 43 1 www.brainheaters.in Q1) Ans: (a) Define ADT

More information

The program simply pushes all of the characters of the string into the stack. Then it pops and display until the stack is empty.

The program simply pushes all of the characters of the string into the stack. Then it pops and display until the stack is empty. EENG212 Algorithms & Data Structures Fall 0/07 Lecture Notes # Outline Stacks Application of Stacks Reversing a String Palindrome Example Infix, Postfix and Prefix Notations APPLICATION OF STACKS Stacks

More information

CSC 273 Data Structures

CSC 273 Data Structures CSC 273 Data Structures Lecture 3- Stacks Some familiar stacks What is a stack? Add item on top of stack Remove item that is topmost Last In, First Out LIFO Specifications of the ADT Stack Specifications

More information

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1 Data Structure using C++ Lecture 04 Reading Material Data Structures and algorithm analysis in C++ Chapter. 3 3.1, 3.2, 3.2.1 Summary Infix to Postfix Example 1: Infix to Postfix Example 2: Postfix Evaluation

More information

Lecture 12 ADTs and Stacks

Lecture 12 ADTs and Stacks Lecture 12 ADTs and Stacks Modularity Divide the program into smaller parts Advantages Keeps the complexity managable Isolates errors (parts can be tested independently) Can replace parts easily Eliminates

More information

Outline. Introduction Stack Operations Stack Implementation Implementation of Push and Pop operations Applications. ADT for stacks

Outline. Introduction Stack Operations Stack Implementation Implementation of Push and Pop operations Applications. ADT for stacks Stack Chapter 4 Outline Introduction Stack Operations Stack Implementation Implementation of Push and Pop operations Applications Recursive Programming Evaluation of Expressions ADT for stacks Introduction

More information

CMPT 225. Stacks-part2

CMPT 225. Stacks-part2 CMPT 225 Stacks-part2 Converting Infix Expressions to Equivalent Postfix Expressions An infix expression can be evaluated by first being converted into an equivalent postfix expression Facts about converting

More information

Stacks. Ordered list with property: Insertions and deletions always occur at the same end. INSERT DELETE A3 A3 TOP TOP TOP

Stacks. Ordered list with property: Insertions and deletions always occur at the same end. INSERT DELETE A3 A3 TOP TOP TOP Stacks Ordered list with property: Insertions and deletions always occur at the same end. INSERT A3 A3 TOP DELETE A2 TOP A2 A2 TOP A1 A1 A1 A0 A0 A0 Stacks Implementation Implementation with arrays: Declare

More information

12 Abstract Data Types

12 Abstract Data Types 12 Abstract Data Types 12.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define the concept of an abstract data type (ADT). Define

More information

Stacks. CONTENTS 3.1 Introduction 1. Stack as an abstract data type 2. Representation of a Stack as an array 3.2Applications of Stack.

Stacks. CONTENTS 3.1 Introduction 1. Stack as an abstract data type 2. Representation of a Stack as an array 3.2Applications of Stack. Stacks CONTENTS 3.1 Introduction 1. Stack as an abstract data type 2. Representation of a Stack as an array 3.2Applications of Stack Hours: 12 Marks: 18 3.1 Introduction to Stacks 1. Stack as Abstract

More information

CS 211 Programming Practicum Spring 2018

CS 211 Programming Practicum Spring 2018 Due: Thursday, 4/5/18 at 11:59 pm Infix Expression Evaluator Programming Project 5 For this lab, write a C++ program that will evaluate an infix expression. The algorithm REQUIRED for this program will

More information

Stacks, Queues (cont d)

Stacks, Queues (cont d) Stacks, Queues (cont d) CSE 2011 Winter 2007 February 1, 2007 1 The Adapter Pattern Using methods of one class to implement methods of another class Example: using List to implement Stack and Queue 2 1

More information

DS Assignment II. Full Sized Image

DS Assignment II. Full Sized Image DS Assignment II 1. A) For the Towers of Hanoi problem, show the call tree during the recursive call Towers(3, A, C, B). In the tree, label the root node as Towers (3, A, C, B) while marking all the intermediate

More information

CS 211 Programming Practicum Fall 2018

CS 211 Programming Practicum Fall 2018 Due: Wednesday, 11/7/18 at 11:59 pm Infix Expression Evaluator Programming Project 5 For this lab, write a C++ program that will evaluate an infix expression. The algorithm REQUIRED for this program will

More information

CS6202 - PROGRAMMING & DATA STRUCTURES I Unit IV Part - A 1. Define Stack. A stack is an ordered list in which all insertions and deletions are made at one end, called the top. It is an abstract data type

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Linear Structures The structures we ve seen so far, Vectors/ArrayLists and linked lists, allow insertion and deletion of elements

More information

Outline and Reading. The Stack ADT ( 4.2.1) Applications of Stacks ( 4.2.3) Array-based implementation ( 4.2.2) Growable array-based stack.

Outline and Reading. The Stack ADT ( 4.2.1) Applications of Stacks ( 4.2.3) Array-based implementation ( 4.2.2) Growable array-based stack. Stacks Outline and Reading The Stack ADT ( 4.2.1) Applications of Stacks ( 4.2.3) Array-based implementation ( 4.2.2) Growable array-based stack Stacks 2 Abstract Data Types (ADTs) An abstract data type

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

15. Stacks and Queues

15. Stacks and Queues COMP1917 15s2 15. Stacks and Queues 1 COMP1917: Computing 1 15. Stacks and Queues Reading: Moffat, Section 10.1-10.2 Overview Stacks Queues Adding to the Tail of a List Efficiency Issues Queue Structure

More information

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3 UNIT 3 LINEAR DATA STRUCTURES 1. Define Data Structures Data Structures is defined as the way of organizing all data items that consider not only the elements stored but also stores the relationship between

More information

Stacks (Section 2) By: Pramod Parajuli, Department of Computer Science, St. Xavier s College, Nepal.

Stacks (Section 2) By: Pramod Parajuli, Department of Computer Science, St. Xavier s College, Nepal. (Section 2) Linked list implementation of stack Typical Application of stacks Evaluation of expressions (infix, postfix, prefix) References and further details By: Pramod Parajuli, Department of Computer

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours TED (10)-3071 Reg. No.. (REVISION-2010) (Maximum marks: 100) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours PART

More information

Infix to Postfix Conversion

Infix to Postfix Conversion Infix to Postfix Conversion Infix to Postfix Conversion Stacks are widely used in the design and implementation of compilers. For example, they are used to convert arithmetic expressions from infix notation

More information

AIM:- To write a C program to create a singly linked list implementation.

AIM:- To write a C program to create a singly linked list implementation. SINGLY LINKED LIST AIM:- To write a C program to create a singly linked list implementation. ALGORITHM:- 1. Start the program. 2. Get the choice from the user. 3. If the choice is to add records, get the

More information

Foundations of Data Structures

Foundations of Data Structures Foundations of Data Structures Lecture 4 Elementary Abstract Data Types (ADT): Stack Queue 1 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies:

More information

Stacks, Queues and Hierarchical Collections

Stacks, Queues and Hierarchical Collections Programming III Stacks, Queues and Hierarchical Collections 2501ICT Nathan Contents Linked Data Structures Revisited Stacks Queues Trees Binary Trees Generic Trees Implementations 2 Copyright 2002- by

More information

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) Unit - 2 By: Gurpreet Singh Dean Academics & H.O.D. (C.S.E. / I.T.) Yamuna Institute of Engineering & Technology, Gadholi What is a Stack? A stack is a

More information

Data Structure. Chapter 3 Stacks and Queues. Department of Communication Engineering National Central University Jhongli, Taiwan.

Data Structure. Chapter 3 Stacks and Queues. Department of Communication Engineering National Central University Jhongli, Taiwan. Data Structure Chapter 3 Stacks and Queues Instructor: Angela Chih-Wei Tang Department of Communication Engineering National Central University Jhongli, Taiwan 29 Spring Outline Stack Queue A Mazing Problem

More information

CS W3134: Data Structures in Java

CS W3134: Data Structures in Java CS W3134: Data Structures in Java Lecture #10: Stacks, queues, linked lists 10/7/04 Janak J Parekh HW#2 questions? Administrivia Finish queues Stack/queue example Agenda 1 Circular queue: miscellany Having

More information

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms Introduction Problem Solving on Computer Data Structures (collection of data and relationships) Algorithms 1 Objective of Data Structures Two Goals: 1) Identify and develop useful high-level data types

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 11 Introduction to Computing II Wayne Snyder Department Boston University Today Object-Oriented Programming Concluded Stacks, Queues, and Priority Queues as Abstract Data Types Reference types: Basic

More information

Postfix (and prefix) notation

Postfix (and prefix) notation Postfix (and prefix) notation Also called reverse Polish reversed form of notation devised by mathematician named Jan Łukasiewicz (so really lü-kä-sha-vech notation) Infix notation is: operand operator

More information

The Stack and Queue Types

The Stack and Queue Types The Stack and Queue Types Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html 2 Programming Principle of the Day Do the simplest thing that could possibly work A good

More information

CSC 222: Computer Programming II. Spring 2005

CSC 222: Computer Programming II. Spring 2005 CSC 222: Computer Programming II Spring 2005 Stacks and recursion stack ADT push, pop, peek, empty, size ArrayList-based implementation, java.util.stack application: parenthesis/delimiter matching postfix

More information

Outline. Stacks. 1 Chapter 5: Stacks and Queues. favicon. CSI33 Data Structures

Outline. Stacks. 1 Chapter 5: Stacks and Queues. favicon. CSI33 Data Structures Outline Chapter 5: and Queues 1 Chapter 5: and Queues Chapter 5: and Queues The Stack ADT A Container Class for Last-In-First-Out Access A stack is a last in, first out (LIFO) structure, i.e. a list-like

More information

Stacks Fall 2018 Margaret Reid-Miller

Stacks Fall 2018 Margaret Reid-Miller Stacks 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Today: Quiz 5 solutions Recursive add from last week (see SinglyLinkedListR.java) Stacks ADT (Queues on Thursday) ArrayStack

More information

Guide for The C Programming Language Chapter 5

Guide for The C Programming Language Chapter 5 1. Differentiate between primitive data type and non-primitive data type. Primitive data types are the basic data types. These data types are used to represent single values. For example: Character, Integer,

More information

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

8/28/12. Outline. Part 2. Stacks. Linear, time ordered structures. What can we do with Coin dispenser? Stacks

8/28/12. Outline. Part 2. Stacks. Linear, time ordered structures. What can we do with Coin dispenser? Stacks 8/8/ Part Stacks Instructor: Sangmi Pallickara (sangmi@cscolostateedu) Department of Computer Science Linear, time ordered structures Data Structures that reflects a temporal relationship Order of removal

More information

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) WINTER 18 EXAMINATION Subject Name: Data Structure using C Model wer Subject Code: 22317 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given

More information

Bangalore South Campus

Bangalore South Campus USN: 1 P E PESIT Bangalore South Campus Hosur road, 1km before ElectronicCity, Bengaluru -100 Department of Basic Science and Humanities INTERNAL ASSESSMENT TEST 3 Date: 22/11/2017 Time:11:30am- 1.00 pm

More information