Stacks Prepared By : Ramesh Kumar PGT CS(KV Chamera-II(NHPC)

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Algorithm Analysis.
Recursion CS 367 – Introduction to Data Structures.
Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
More on Stacks and Queues. As we mentioned before, two common introductory Abstract Data Type (ADT) that worth studying are Stack and Queue Many problems.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Data Structure Dr. Mohamed Khafagy.
Abstract Data Types (ADT) Collection –An object that can hold a list of other objects Homogeneous Collection –Contains elements all of the same type –Example:
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks CS 3358 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
Topic 15 Implementing and Using Stacks
Stacks. What is a stack? Last-in first-out data structure (LIFO) New objects are placed on top Removal restricted to top object Examples?
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.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
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.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
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. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
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,
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Implementing Stacks Using Arrays CSC 1401: Introduction to Programming with Java Week 14 – Lecture 1 Wanda M. Kunkle.
TCSS 342, Winter 2005 Lecture Notes
Topic 15 Implementing and Using Stacks
Stacks, Queues, and Deques
Stacks, Queues, and Deques
Chapter 7 Stacks II CS Data Structures I COSC 2006
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Data Structures: CSCI 362 – Stack Implementation Data Structures: CSCI 362 – Stack Implementation lecture notes adapted from Data Structures with C++ using.
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,
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.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
Data structures Abstract data types Java classes for Data structures and ADTs.
1 The Stack Class Final Review Fall 2005 CS 101 Aaron Bloomfield.
Graphs – Part II CS 367 – Introduction to Data Structures.
For more notes and topics VISIT: IMPLEMENTATION OF STACKS eITnotes.com.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Data Structures & Algorithms
AITI Lecture 18 Introduction to Data Structure, Stack, and Queue Adapted from MIT Course 1.00 Spring 2003 Lecture 23 and Tutorial Note 8 (Teachers: Please.
Stacks Nour El-Kadri CSI Stacks Software stacks are abstract data types (structures) similar to physical stacks, Plates Trays Books PEZ dispenser.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
ITI Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
Stacks This presentation shows – how to implement the stack – how it can be used in real applications.
Computer Science Department Data Structure and Algorithms Lecture 3 Stacks.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Stack. ADS2 Lecture 1010 The Stack ADT (GoTa §5.1) The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in.
CSE 3358 NOTE SET 8 Data Structures and Algorithms.
Queues CS 367 – Introduction to Data Structures. Queue A queue is a data structure that stores data in such a way that the last piece of data stored,
Click to edit Master text styles Stacks Data Structure.
Linked Lists CS 367 – Introduction to Data Structures.
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
Stacks.
Stacks.
COMPUTER 2430 Object Oriented Programming and Data Structures I
Pointers and Dynamic Variables
Stacks: Implemented using Linked Lists
Stacks and Queues 1.
Topic 15 Implementing and Using Stacks
Stacks, Queues, and Deques
Presentation transcript:

Stacks Prepared By : Ramesh Kumar PGT CS(KV Chamera-II(NHPC)

Stack A stack is a data structure that stores data in such a way that the last piece of data stored, is the first one retrieved –also called last-in, first-out Only access to the stack is the top element –consider trays in a cafeteria to get the bottom tray out, you must first remove all of the elements above

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

Stack A X R C push(M) A X R C M item = pop() item = M A X R C

Implementing a Stack At least three different ways to implement a stack –array –vector –linked list Which method to use depends on the application –what advantages and disadvantages does each implementation have?

Implementing Stacks: Array Advantages –best performance Disadvantage –fixed size Basic implementation –initially empty array –field to record where the next data gets placed into –if array is full, push() returns false otherwise adds it into the correct spot –if array is empty, pop() returns null otherwise removes the next item in the stack

Stack Class (array based) class StackArray { private Object[ ] stack; private int nextIn; public StackArray(int size) { stack = new Object[size]; nextIn = 0; } public boolean push(Object data); public Object pop(); public void clear(); public boolean isEmpty(); public boolean isFull(); }

push() Method (array based) public boolean push(Object data) { if(nextIn == stack.length) { return false; } // stack is full // add the element and then increment nextIn stack[nextIn] = data; nextIn++; return true; }

pop() Method (array based) public Object pop() { if(nextIn == 0) { return null; } // stack is empty // decrement nextIn and return the data nextIn--; Object data = stack[nextIn]; return data; }

Notes on push() and pop() Other ways to do this even if using arrays –may want to keep a size variable that tracks how many items in the list –may want to keep a maxSize variable that stores the maximum number of elements the stack can hold (size of the array) you would have to do this in a language like C++ –could add things in the opposite direction keep track of nextOut and decrement it on every push; increment it on every pop

Remaining Methods (array based) public void clear() { nextIn = 0; } public boolean isEmpty() { return nextIn == 0; } public boolean isFull() { return nextIn == stack.length; }

Additional Notes Notice that the array is considered empty if nextIn equals zero –doesn’t matter if there is more data stored in the array – it will never be retrieved pop() method will automatically return For a truly robust implementation –should set array elements equal to null if they are not being used why? how?

Implementing a Stack: Vector Advantages –grows to accommodate any amount of data –second fastest implementation when data size is less than vector size Disadvantage –slowest method if data size exceeds current vector size have to copy everything over and then add data –wasted space if anomalous growth vectors only grow in size – they don’t shrink –can grow to an unlimited size I thought this was an advantage? Basic implementation –virtually identical to array based version

Stack Class (vector based) class StackVector { private Object[ ] stack; private int nextIn; public StackVector(int initialSize) { stack = new Object[initialSize]; nextIn = 0; } public void push(Object data); public Object pop(); public void clear(); public boolean isEmpty(); }

push() Method (vector based) public void push(Object data) { // see if we need to grow this stack if(nextIn == stack.length) { Object [ ] tmp = new Object[stack.length * 2]; for(int i=0; i<stack.length; i++) tmp[i] = stack[i]; stack = tmp; } // now add the element and increment nextIn stack[nextIn] = data; nextIn++; }

pop() Method (vector based) public Object pop() { if(nextIn == 0) { return null; } // stack empty // decrement nextIn, get the data, and return it nextIn--; Object data = stack[nextIn]; return data; }

Notes on push() and pop() Notice that the pop() method is identical to that for an array based version Only difference is in push() method –doesn’t return a boolean because it cannot fail unless we run out of memory  –first checks if the push will exceed the current array if so, create a new array that’s 2x as big, copy data, and make that the new stack this is the case that’s very slow

Remaining Methods (vector based) The clear() and isEmpty() methods are identical to those in an array based stack implementation There is no need for an isFull() method –why?

Implementing a Stack: Linked List Advantages: –always constant time to push or pop an element –can grow to an infinite size Disadvantages –the common case is the slowest of all the implementations –can grow to an infinite size Basic implementation –list is initially empty –push() method adds a new item to the head of the list –pop() method removes the head of the list

Stack Class (list based) class StackList { private LinkedList list; public StackList() { list = new LinkedList(); } public void push(Object data) { list.addHead(data); } public Object pop() { return list.deleteHead(); } public void clear() { list.clear(); } public boolean isEmpty() { return list.isEmpty(); } }

Additional Notes It should appear obvious that linked lists are very well suited for stacks –addHead() and deleteHead() are basically the push() and pop() methods Our original list implementation did not have a clear() method –it’s very simple to do –how would you do it? Again, no need for the isFull() method –list can grow to an infinite size

Stack Applications Stacks are a very common data structure –compilers parsing data between delimiters (brackets) –operating systems program stack –virtual machines manipulating numbers –pop 2 numbers off stack, do work (such as add) –push result back on stack and repeat –artificial intelligence finding a path

Reverse Polish Notation Way of inputting numbers to a calculator –(5 + 3) * 6 becomes * –5 + 3 * 6 becomes * + We can use a stack to implement this –consider * * 6 48 –try doing * +

public int rpn(String equation) { StackList stack = new StackList(); StringTokenizer tok = new StringTokenizer(equation); while(tok.hasMoreTokens()) { String element = tok.nextToken(); if(isOperator(element)) { char op = element.charAt(0); if(op == ‘=‘) { int result = ((Integer)stack.pop()).intValue(); if(!stack.isEmpty() || tok.hasMoreTokens()) { return Integer.MAX_VALUE; } // error else { return result; } } else { Integer op1 = (Integer)stack.pop() Integer op2 = (Integer)stack.pop(); if((op1 == null) || (op2 == null)) { return Integer.MAX_VALUE; } stack.push(doOperation(op, op1, op2)); } else { Integer operand = new Integer(Integer.parseInt(element)); stack.push(operand); } return Integer.MAX_VALUE; }

Finding a Path Consider the following graph of flights PRXQ W YZST Key : city (represented as C) : flight from city C 1 to city C 2 C 1 C 2 flight goes from W to S W S Example

Finding a Path If it exists, we can find a path from any city C 1 to another city C 2 using a stack –place the starting city on the bottom of the stack mark it as visited pick any arbitrary arrow out of the city –city cannot be marked as visited place that city on the stack –also mark it as visited if that’s the destination, we’re done otherwise, pick an arrow out of the city currently at –next city must not have been visited before –if there are no legitimate arrows out, pop it off the stack and go back to the previous city repeat this process until the destination is found or all the cities have been visited

Example Want to go from P to Y –push P on the stack and mark it as visited –pick R as the next city to visit (random select) push it on the stack and mark it as visited –pick X as the next city to visit (only choice) push it on the stack and mark it as visited –no available arrows out of X – pop it –no more available arrows from R – pop it –pick W as next city to visit (only choice left) push it on the stack and mark it as visited –pick Y as next city to visit (random select) this is the destination – all done

Psuedo-Code for the Example public boolean findPath(City origin, City destination) { StackArray stack = new Stack(numCities); clearAllCityMarks(); stack.push(origin); origin.mark(); while(!stack.isEmpty()) { City next = pickCity(); if(next == destination) { return true; } if(next != null) { stack.push(next); } else { stack.pop(); } // no valid arrows out of city } return false; }