Introduction to Stacks



Similar documents
Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Data Structures and Algorithms V Otávio Braga

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2

7.1 Our Current Model

DATA STRUCTURES USING C

Module 2 Stacks and Queues: Abstract Data Types

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Algorithms and Data Structures

STACKS,QUEUES, AND LINKED LISTS

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Stacks. Data Structures and Data Types. Collections

Chapter 3: Restricted Structures Page 1

CS 111 Classes I 1. Software Organization View to this point:

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

Application of Stacks: Postfix Expressions Calculator (cont d.)

14 Stacks, Queues, And Linked Lists

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Data Structures Using C++ 2E. Chapter 5 Linked Lists

D06 PROGRAMMING with JAVA

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Moving from CS 61A Scheme to CS 61B Java

Section IV.1: Recursive Algorithms and Recursion Trees

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Data Structures in the Java API

Computer Programming I

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Analysis of a Search Algorithm

Statements and Control Flow

Monitors, Java, Threads and Processes

DATA STRUCTURE - STACK

10CS35: Data Structures Using C

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Stack Allocation. Run-Time Data Structures. Static Structures

Common Data Structures

Chapter 5 Instructor's Manual

Habanero Extreme Scale Software Research Project

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Data Structures and Algorithms Stacks and Queues

Linear ADTs. Restricted Lists. Stacks, Queues. ES 103: Data Structures and Algorithms 2012 Instructor Dr Atul Gupta

COMPUTER SCIENCE. Paper 1 (THEORY)

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

CmpSci 187: Programming with Data Structures Spring 2015

Inside the Java Virtual Machine

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Chapter 7D The Java Virtual Machine

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Data Structures and Algorithms

Example of a Java program

Object Oriented Software Design

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Java Interview Questions and Answers

Introduction to Programming System Design. CSCI 455x (4 Units)

CS 2412 Data Structures. Chapter 2 Stacks and recursion

Atmiya Infotech Pvt. Ltd. Data Structure. By Ajay Raiyani. Yogidham, Kalawad Road, Rajkot. Ph : ,

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Computing Concepts with Java Essentials

Basic Programming and PC Skills: Basic Programming and PC Skills:

Introduction to Java

Software Engineering Techniques

CompSci-61B, Data Structures Final Exam

PES Institute of Technology-BSC QUESTION BANK

Data Structure [Question Bank]

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

PSTricks. pst-ode. A PSTricks package for solving initial value problems for sets of Ordinary Differential Equations (ODE), v0.7.

Class 32: The Java Collections Framework

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Chapter 8: Bags and Sets

Java Program Coding Standards Programming for Information Technology

Binary Search Trees. basic implementations randomized BSTs deletion in BSTs

Stacks. Linear data structures

Data Structures UNIT III. Model Question Answer

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Linked Lists Linked Lists, Queues, and Stacks

Administrative Issues

Binary Search Trees (BST)

Chapter 5. Recursion. Data Structures and Algorithms in Java

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Object Oriented Software Design

COMP 356 Programming Language Structures Notes for Chapter 4 of Concepts of Programming Languages Scanning and Parsing

Compilers I - Chapter 4: Generating Better Code

Glossary of Object Oriented Terms

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Introduction to Data Structures

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Data Structure with C

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Chapter 2: Elements of Java

Universidad Carlos III de Madrid

Transcription:

Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack.

What is a Stack? Stack is a data structure in which data is added and removed at only one end called the top. To add (push) an item to the stack, it must be placed on the top of the stack. To remove (pop) an item from the stack, it must be removed from the top of the stack too. Thus, the last element that is pushed into the stack, is the first element to be popped out of the stack. i.e., Last In First Out (LIFO)

An Example of Stack top 8 top 2 8 top 1 7 Push(8) 1 7 Push(2) 1 7 2 2 2 pop() top 7 2 pop() top 1 7 2 pop() top 8 1 7 2

Stack Implementations public interface Stack extends Container { public abstract Object gettop(); public abstract void push(object obj); public abstract Object pop(); In our implementation, a stack is a container that extends the AbstractContainer class and implements the Stack interface. Two implementations: StackAsArray The underlying data structure is an array of Object StackAsLinkedList The underlying data structure is an object of MyLinkedList

StackAsArray Constructor In the StackAsArray implementation that follows, the top of the stack is array[count 1] and the bottom is array[0]: The constructor s single parameter, size, specifies the maximum number of items that can be stored in the stack. The variable array is initialized to be an array of length size. public class StackAsArray extends AbstractContainer implements Stack { protected Object[] array; public StackAsArray(int size){ array = new Object[size]; //

StackAsArray purge() Method The purpose of the purge method is to remove all the contents of a container. To empty the stack, the purge method simply assigns the value null to the first count positions of the array. public void purge(){ while (count > 0) array[--count] = null; Complexity is O(n)

StackAsArray push() Method push() method adds an element at the top the stack. It takes as argument an Object to be pushed. It first checks if there is room left in the stack. If no room is left, it throws a ContainerFullException exception. Otherwise, it puts the object into the array, and then increments count variable by one. public void push(object object){ if (count == array.length) throw new ContainerFullException(); else array[count++] = object; Complexity is O(1)

StackAsArray pop() Method The pop method removes an item from the stack and returns that item. The pop method first checks if the stack is empty. If the stack is empty, it throws a ContainerEmptyException. Otherwise, it simply decreases count by one and returns the item found at the top of the stack. public Object pop(){ if(count == 0) throw new ContainerEmptyException(); else { Object result = array[--count]; array[count] = null; return result; Complexity is O(1)

StackAsArray gettop() Method gettop() method first checks if the stack is empty. gettop() method is a stack accessor which returns the top item in the stack without removing that item. If the stack is empty, it throws a ContainerEmptyException. Otherwise, it returns the top item found at position count-1. public Object gettop(){ if(count == 0) throw new ContainerEmptyException(); else return array[count 1]; Complexity is O(1)

StackAsArray iterator() Method public Iterator iterator() { return new Iterator() { private int position = count-1; public boolean hasnext() { return position >=0; public Object next () { if(position < 0) throw new NoSuchElementException(); else return array[position--]; ;

StackAsLinkedList Implementation public class StackAsLinkedList extends AbstractContainer implements Stack { protected MyLinkedList list; public StackAsLinkedList(){ list = new MyLinkedList(); public void purge(){ list.purge(); count = 0; Complexity is O(1) //

StackAsLinkedList Implementation (Cont.) public void push(object obj){ list.prepend(obj); count++; public Object pop(){ if(count == 0) throw new ContainerEmptyException(); else{ Object obj = list.getfirst(); list.extractfirst(); count--; Complexity is O(1) return obj; public Object gettop(){ if(count == 0) throw new ContainerEmptyException(); else return list.getfirst(); Complexity is O(1) Complexity is O(1)

StackAsLinkedList Implementation (Cont.) public Iterator iterator() { return new Iterator() { private MyLinkedList.Element position = list.gethead(); public boolean hasnext() { return position!= null; ; public Object next() { if(position == null) throw new NoSuchElementException(); else { Object obj = position.getdata(); position = position.getnext(); return obj;

Applications of Stack Some direct applications: Page-visited history in a Web browser Undo sequence in a text editor Chain of method calls in the Java Virtual Machine Evaluating postfix expressions Some indirect applications Auxiliary data structure for some algorithms Component of other data structures

Application of Stack - Evaluating Postfix Expression (5+9)*2+6*5 An ordinary arithmetical expression like the above is called infixexpression -- binary operators appear in between their operands. The order of operations evaluation is determined by the precedence rules and parenthesis. When an evaluation order is desired that is different from that provided by the precedence, parentheses are used to override precedence rules.

Application of Stack - Evaluating Postfix Expression Expressions can also be represented using postfix notation - where an operator comes after its two operands. The advantage of postfix notation is that the order of operation evaluation is unique without the need for precedence rules or parenthesis. Infix 16 / 2 (2 + 14)* 5 2 + 14 * 5 (6 2) * (5 + 4) Postfix 16 2 / 2 14 + 5 * 2 14 5 * + 6 2-5 4 + *

Application of Stack - Evaluating Postfix Expression The following algorithm uses a stack to evaluate a postfix expressions. Start with an empty stack for (each item in the expression) { if (the item is a number) Push the number onto the stack else if (the item is an operator){ Pop two operands from the stack Apply the operator to the operands Push the result onto the stack Pop the only one number from the stack that s the result of the evaluation

Application of Stack - Evaluating Postfix Expression Example: Consider the postfix expression, 2 10 + 9 6 - /, which is (2 + 10) / (9-6) in infix, the result of which is 12 / 3 = 4. The following is a trace of the postfix evaluation algorithm for the above.