Algorithms. Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications

Size: px
Start display at page:

Download "Algorithms. Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications"

Transcription

1 Algithms Stacks and queues 1.3 BAGS, QUEUES, AND STACKS Fundamental data types. Value: collection of objects. Operations: insert, remove, iterate, test if empty. Intent is clear when we insert. Which item do we remove? Algithms F O U R T H E D I T I O N stacks resizing arrays queues generics iterars applications stack queue enqueue Stack. Examine the item most recently added. push pop dequeue LIFO = "last in out" Queue. Examine the item least recently added. FIFO = " in out" 2 Client, implementation, interface Separate interface and implementation. Ex: stack, queue, bag, priity queue, symbol table, union-find,. Benefits. Client can't know details of implementation client has many implementation from which choose. Implementation can't know details of client needs many clients can re-use the same implementation. Design: creates modular, reusable libraries. Perfmance: use optimized implementation where it matters. Client: program using operations defined in interface. Implementation: actual code implementing operations. Interface: description of data type, basic operations. Algithms BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications 3

2 Stack API Stack test client Warmup API. Stack of strings data type. public class StackOfStrings push pop Read strings from standard input. If string equals "-", pop string from stack and print. Otherwise, push string on stack. push pop StackOfStrings() create an empty stack void push(string item) insert a new string on stack String pop() remove and return the string most recently added boolean isempty() is the stack empty? int size() numr of strings on the stack public static void main(string[] args) StackOfStrings stack = new StackOfStrings(); while (!StdIn.isEmpty()) String s = StdIn.readString(); if (s.equals("-")) StdOut.print(stack.pop()); else stack.push(s); % me.txt that is Warmup client. Reverse sequence of strings from standard input. % java StackOfStrings <.txt that 5 6 Stack: linked-list representation Stack pop: linked-list implementation Maintain pointer node in a linked list; insert/remove from front. StdIn StdOut save item return String item =.item; delete node insert at front of linked list remove from front of linked list inner class String item; =.next; return saved item 7 8

3 Stack push: linked-list implementation Stack: linked-list implementation in Java save a link the list Node old = ; public class LinkedStackOfStrings private Node = ; old String item; private inner class (access modifiers don't matter) inner class String item; create a new node f the ginning = new Node(); old set the instance variables in the new node return == ; public void push(string item) Node old = ; = new Node();.item = item;.next = old;.item = "";.next = old; String item =.item; =.next; 9 10 Stack: linked-list implementation perfmance Stack: array implementation Proposition. Every operation takes constant time in the wst case. Proposition. A stack with N items uses ~ 40 N bytes. Array implementation of a stack. Use array s[] sre N items on stack. push(): add new item at s[n]. pop(): remove item from s[n-1]. inner class String item; object overhead extra overhead item next references 16 bytes (object overhead) 8 bytes (inner class extra overhead) 8 bytes (reference String) 8 bytes (reference Node) 40 bytes per stack node s[] N capacity = 10 Remark. This accounts f the memy f the stack (but the memy f strings themselves, which the client owns). Defect. Stack overflows when N exceeds capacity. [stay tuned] 11 12

4 Stack: array implementation Stack considerations public class FixedCapacityStackOfStrings private String[] s; private int N = 0; public FixedCapacityStackOfStrings(int capacity) s = new String[capacity]; return N == 0; a cheat (stay tuned) Overflow and underflow. Underflow: throw exception if pop from an empty stack. Overflow: use resizing array f array implementation. [stay tuned] Null items. We allow items inserted. Loitering. Holding a reference an object when it is no longer needed. use index in array; then increment N public void push(string item) s[n++] = item; return s[--n]; return s[--n]; loitering String item = s[--n]; s[n] = ; decrement N; then use index in array this version avoids "loitering": garbage collecr can reclaim memy only if no outstanding references Stack: resizing-array implementation Problem. Requiring client provide capacity does implement API! Q. How grow and shrink array? Algithms BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications First try. push(): increase size of array s[] by 1. pop(): decrease size of array s[] by 1. Too expensive. Need copy all items a new array. Inserting N items takes time proptional N ~ N 2 / 2. infeasible f large N Challenge. Ensure that array resizing happens infrequently. 16

5 Stack: resizing-array implementation Q. How grow array? "repeated doubling" A. If array is full, create a new array of twice the size, and copy items. public ResizingArrayStackOfStrings() s = new String[1]; Stack: amtized cost of adding a stack Cost of inserting N items. N + ( N) ~ 3N. 1 array access per push k array accesses double size k (igning cost create new array) public void push(string item) if (N == s.length) resize(2 * s.length); s[n++] = item; private void resize(int capacity) String[] copy = new String[capacity]; f (int i = 0; i < N; i++) copy[i] = s[i]; s = copy; see next slide 128 cost (array accesses) 0 one gray dot f each operation red dots give cumulative average 3 0 numr of push() operations 128 Consequence. Inserting N items takes time proptional N ( N 2 ) Stack: resizing-array implementation Stack: resizing-array implementation Q. How shrink array? Q. How shrink array? First try. push(): double size of array s[] when array is full. pop(): halve size of array s[] when array is one-half full. Too expensive in wst case. Consider push-pop-push-pop- sequence when array is full. Each operation takes time proptional N. N = 5 Efficient solution. push(): double size of array s[] when array is full. pop(): halve size of array s[] when array is one-quarter full. String item = s[--n]; s[n] = ; if (N > 0 && N == s.length/4) resize(s.length/2); N = 4 N = 5 N = 4 Invariant. Array is tween 25% and 100% full

6 Stack: resizing-array implementation trace Stack resizing-array implementation: perfmance push() pop() N a.length a[] that 4 8 that - that is 2 2 is Trace of array resizing during a sequence of push() and pop() operations Amtized analysis. Average running time per operation over a wst-case sequence of operations. Proposition. Starting from an empty stack, any sequence of M push and pop operations takes time proptional M. construct push pop size st wst amtized N 1 1 N der of growth of running time f resizing stack with N items doubling and halving operations Stack resizing-array implementation: memy usage Stack implementations: resizing array vs. linked list Proposition. Uses tween ~ 8 N and ~ 32 N bytes represent a stack with N items. ~ 8 N when full. ~ 32 N when one-quarter full. public class ResizingArrayStackOfStrings private String[] s; private int N = 0; 8 bytes (reference array) 24 bytes (array overhead) 8 bytes array size 4 bytes (int) 4 bytes (padding) Tradeoffs. Can implement a stack with either resizing array linked list; client can use interchangeably. Which one is tter? Linked-list implementation. Every operation takes constant time in the wst case. Uses extra time and space deal with the links. Resizing-array implementation. Every operation takes constant amtized time. Less wasted space. N = 4 Remark. This accounts f the memy f the stack (but the memy f strings themselves, which the client owns)

7 Queue API enqueue public class QueueOfStrings 1.3 BAGS, QUEUES, AND STACKS QueueOfStrings() create an empty queue void enqueue(string item) insert a new string on queue Algithms stacks resizing arrays queues generics String dequeue() remove and return the string least recently added boolean isempty() is the queue empty? int size() numr of strings on the queue iterars dequeue applications 26 Queue: linked-list representation Queue dequeue: linked-list implementation Maintain pointer and last nodes in a linked list; insert/remove from opposite ends. save item return String item =.item; StdIn StdOut delete node =.next; last insert at end of linked list inner class String item; last last remove from front of linked list - return saved item - Remark. Identical code linked-list stack pop()

8 Queue enqueue: linked-list implementation Queue: linked-list implementation in Java save a link the last node Node oldlast = last; oldlast last public class LinkedQueueOfStrings private Node, last; /* same as in StackOfStrings */ return == ; inner class String item; create a new node f the end last = new Node(); last.item = ""; link the new node the end of the list oldlast.next = last; oldlast oldlast last last public void enqueue(string item) Node oldlast = last; last = new Node(); last.item = item; last.next = ; if (isempty()) = last; else oldlast.next = last; public String dequeue() String item =.item; =.next; if (isempty()) last = ; special cases f empty queue Queue: resizing array implementation Array implementation of a queue. Use array q[] sre items in queue. enqueue(): add new item at q[tail]. q[] dequeue(): remove item from q[head]. Update head and tail modulo the capacity. Add resizing array. the st of times head tail capacity = 10 Algithms BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications Q. How resize? 31

9 Parameterized stack Parameterized stack We implemented: StackOfStrings. We implemented: StackOfStrings. We also want: StackOfURLs, StackOfInts, StackOfVans,. We also want: StackOfURLs, StackOfInts, StackOfVans,. Attempt 1. Implement a separate stack class f each type. Attempt 2. Implement a stack with items of type Object. Rewriting code is tedious and err-prone. Maintaining cut-and-pasted code is tedious and err-prone. Casting is required in client. Casting is err-prone: run-time err if types mismatch. StackOfObjects s = new most reasonable approach until Java 1.5. Apple a = new Apple(); Orange b = new Orange(); s.push(a); s.push(b); a = (Apple) (s.pop()); run-time err 33 Parameterized stack 34 Generic stack: linked-list implementation We implemented: StackOfStrings. public class LinkedStackOfStrings private Node = ; We also want: StackOfURLs, StackOfInts, StackOfVans,. String item; Attempt 3. Java generics. Avoid casting in client. Discover type mismatch errs at compile-time instead of run-time. return == ; type parameter Stack<Apple> s = new Stack<Apple>(); Apple a = new Apple(); Orange b = new Orange(); s.push(a); s.push(b); public class Stack<Item> private Node = ; compile-time err a = s.pop(); Item item; return == ; generic type name public void push(string item) Node old = ; = new Node();.item = item;.next = old; public void push(item item) Node old = ; = new Node();.item = item;.next = old; String item =.item; =.next; public Item pop() Item item =.item; =.next; Guiding principles. Welcome compile-time errs; avoid run-time errs

10 Generic stack: array implementation Generic stack: array implementation the way it should the way it is public class FixedCapacityStackOfStrings private String[] s; private int N = 0; public class FixedCapacityStack<Item> private Item[] s; private int N = 0; public class FixedCapacityStackOfStrings private String[] s; private int N = 0; public class FixedCapacityStack<Item> private Item[] s; private int N = 0; public..stackofstrings(int capacity) s = new String[capacity]; public FixedCapacityStack(int capacity) s = new Item[capacity]; public..stackofstrings(int capacity) s = new String[capacity]; public FixedCapacityStack(int capacity) s = (Item[]) new Object[capacity]; return N == 0; return N == 0; return N == 0; return N == 0; public void push(string item) s[n++] = item; public void push(item item) s[n++] = item; public void push(string item) s[n++] = item; public void push(item item) s[n++] = item; return s[--n]; public Item pop() return s[--n]; return s[--n]; public Item pop() return generic array creation allowed in Java the ugly cast Unchecked cast Generic data types: auboxing Q. What do about primitive types? % javac FixedCapacityStack.java Note: FixedCapacityStack.java uses unchecked unsafe operations. Note: Recompile with -Xlint:unchecked f details. % javac -Xlint:unchecked FixedCapacityStack.java FixedCapacityStack.java:26: warning: [unchecked] unchecked cast found : java.lang.object[] required: Item[] 1 warning a = (Item[]) new Object[capacity]; ^ Wrapper type. Each primitive type has a wrapper object type. Ex: Integer is wrapper type f int. Auboxing. Aumatic cast tween a primitive type and its wrapper. Stack<Integer> s = new Stack<Integer>(); s.push(17); // s.push(integer.valueof(17)); int a = s.pop(); // int a = s.pop().intvalue(); Botm line. Client code can use generic stack f any type of data

11 Iteration Design challenge. Suppt iteration over stack items by client, without revealing the internal representation of the stack. 1.3 BAGS, QUEUES, AND STACKS s[] i it was the st of times N Algithms stacks resizing arrays queues generics iterars applications current times of st the was it Java solution. Make stack implement the java.lang.iterable interface. 42 Iterars Q. What is an Iterable? A. Has a method that returns an Iterar. Iterable interface public interface Iterable<Item> Iterar<Item> iterar(); Stack iterar: linked-list implementation impt java.util.iterar; public class Stack<Item> implements Iterable<Item>... Q. What is an Iterar? A. Has methods hasnext() and next(). Q. Why make data structures Iterable? A. Java suppts elegant client code. feach statement (shthand) f (String s : stack) StdOut.println(s); Iterar interface public interface Iterar<Item> boolean hasnext(); Item next(); void remove(); equivalent code (longhand) optional; use at your own risk Iterar<String> i = stack.iterar(); while (i.hasnext()) String s = i.next(); StdOut.println(s); 43 public Iterar<Item> iterar() return new ListIterar(); private class ListIterar implements Iterar<Item> private Node current = ; public boolean hasnext() return current!= ; public void remove() /* suppted */ public Item next() Item item = current.item; current = current.next; current throw UnsupptedOperationException throw NoSuchElementException if no me items in iteration times of st the was it 44

12 Stack iterar: array implementation Iteration: concurrent modification impt java.util.iterar; public class Stack<Item> implements Iterable<Item> public Iterar<Item> iterar() return new ReverseArrayIterar(); Q. What if client modifies the data structure while iterating? A. A fail-fast iterar throws a java.util.concurrentmodificationexception. concurrent modification f (String s : stack) stack.push(s); private class ReverseArrayIterar implements Iterar<Item> private int i = N; public boolean hasnext() return i > 0; public void remove() /* suppted */ public Item next() return s[--i]; i N To detect: Count tal numr of push() and pop() operations in Stack. Save counts in *Iterar subclass upon creation. If, when calling next() and hasnext(), the current counts do equal the saved counts, throw exception. s[] it was the st of times Java collections library List interface. java.util.list is API f an sequence of items. Algithms BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications public interface List<Item> implements Iterable<Item> List() create an empty list boolean isempty() is the list empty? int size() numr of items void add(item item) append item the end Item get(int index) return item at given index Item remove(int index) return and delete item at given index boolean contains(item item) does the list contain the given item? Itearr<Item> iterar() iterar over all items in the list... Implementations. java.util.arraylist uses resizing array; java.util.linkedlist uses linked list. caveat: only some operations are efficient 48

13 Java collections library Java collections library java.util.stack. java.util.stack. Suppts push(), pop(), and and iteration. Extends java.util.vecr, which implements java.util.list Suppts push(), pop(), and and iteration. Extends java.util.vecr, which implements java.util.list interface from previous slide, including get() and remove(). interface from previous slide, including get() and remove(). Bloated and poly-designed API (why?) Bloated and poly-designed API (why?) Java 1.3 bug rept (June 27, 2001) The iterar method on java.util.stack iterates through a Stack from the botm up. One would think that it should iterate as if it were popping off the p of the Stack. status (closed, will fix) java.util.queue. An interface, an implementation of a queue. It was an increct design decision have Stack extend Vecr ("is-a" rather than "has-a"). We sympathize with the submitter but can fix this cause of compatibility. Best practices. Use our implementations of Stack, Queue, and Bag. 49 War sry (from Assignment 1) Stack applications Generate random open sites in an N-by-N percolation system. Jenny: percolates blocked pick (i, j) at random; if already open, repeat. does percolate site Takes ~ c1 N 2 seconds. Kenny: create a java.util.arraylist of N 2 closed sites. Pick an index at random and delete. open Takes ~ c2 N 4 seconds. 50 site open site connected p no open site connected p Parsing in a compiler. Java virtual machine. Undo in a wd process. Back butn in a Web browser. PostScript language f printers. Implementing function calls in a compiler.... Why is my program so slow? Kenny Lesson. Don't use a library until you understand its API! This course. Can't use a library until we've implemented it in class

14 Function calls Arithmetic expression evaluation How a compiler implements a function. Function call: push local environment and return address. Return: pop return address and local environment. Recursive function. Function that calls itself. Note. Can always use an explicit stack remove recursion. gcd (216, 192) static int gcd(int p, int q) p = 216, q = 192 if (q == 0) return p; else return gcd(q, gcd p %(192, q); 24) static int gcd(int p, int q) p = 192, q = 24 if (q == 0) return p; else return gcd(q, p gcd % (24, q); 0) static int gcd(int p, int q) if (q == 0) return p; p = 24, q = 0 else return gcd(q, p % q); Goal. Evaluate infix expressions. ( 1 + ( ( ) * ( 4 * 5 ) ) ) Two-stack algithm. [E. W. Dijkstra] Value: push on the value stack. Operar: push on the operar stack. operand Left parenthesis: igne. Right parenthesis: pop operar and two values; push the result of applying that operar those values on the operand stack. Context. An interpreter! operar value stack operar stack * * * * * * * ( 1 + ( ( ) * ( 4 * 5 ) ) ) + ( ( ) * ( 4 * 5 ) ) ) ( ( ) * ( 4 * 5 ) ) ) + 3 ) * ( 4 * 5 ) ) ) 3 ) * ( 4 * 5 ) ) ) ) * ( 4 * 5 ) ) ) * ( 4 * 5 ) ) ) ( 4 * 5 ) ) ) * 5 ) ) ) 5 ) ) ) ) ) ) ) ) ) Dijkstra's two-stack algithm demo Arithmetic expression evaluation infix expression value stack operar stack (fully parenthesized) ( 1 + ( ( ) * ( 4 * 5 ) ) ) operand operar 55 public class Evaluate public static void main(string[] args) Stack<String> ops = new Stack<String>(); Stack<Double> vals = new Stack<Double>(); while (!StdIn.isEmpty()) String s = StdIn.readString(); if (s.equals("(")) ; else if (s.equals("+")) ops.push(s); else if (s.equals("*")) ops.push(s); else if (s.equals(")")) String op = ops.pop(); if (op.equals("+")) vals.push(vals.pop() + vals.pop()); else if (op.equals("*")) vals.push(vals.pop() * vals.pop()); else vals.push(double.parsedouble(s)); StdOut.println(vals.pop()); % java Evaluate ( 1 + ( ( ) * ( 4 * 5 ) ) )

15 Crectness Stack-based programming languages Q. Why crect? A. When algithm encounters an operar surrounded by two values within parentheses, it leaves the result on the value stack. Observation 1. Dijkstra's two-stack algithm computes the same value if the operar occurs after the two values. ( 1 + ( ( ) * ( 4 * 5 ) ) ) ( 1 ( ( ) ( 4 5 * ) * ) + ) as if the iginal input were: ( 1 + ( 5 * ( 4 * 5 ) ) ) Observation 2. All of the parentheses are redundant! Repeating the argument: * * + Jan Lukasiewicz ( 1 + ( 5 * 20 ) ) ( ) 101 Extensions. Me ops, precedence der, associativity. Botm line. Postfix "reverse Polish" ation. Applications. Postscript, Fth, calculars, Java virtual machine, 57 58

Algorithms. Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications

Algorithms. Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications Algithms ROBERT SEDGEWICK KEVIN WAYNE Stacks and queues 1.3 BAGS, QUEUES, AND STACKS Fundamental data types. Value: collection of objects. Operations: add, remove, iterate, test if empty. Intent is clear

More information

Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications. Is Polleverywhere working?

Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications. Is Polleverywhere working? Is Polleverywhere wking? Algithms ROBERT SEDGEWICK KEVIN WAYNE 1.3 BAGS, QUEUES, AND STACKS Algithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE http://algs4.cs.princen.edu stacks resizing arrays

More information

Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays. queue. generics. applications. Stacks and queues

Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays. queue. generics. applications. Stacks and queues ROBERT SEDGEWICK KEVIN WAYNE Algithms ROBERT SEDGEWICK KEVIN WAYNE Stacks and queues Algithms F O U R T H E D I T I O N http://algs4.cs.princen.edu 1.3 BAGS, QUEUES, AND STACKS stacks resizing arrays queues

More information

Algorithms. Algorithms 1.3 STACKS AND QUEUES. stacks resizing arrays queues generics iterators applications ROBERT SEDGEWICK KEVIN WAYNE.

Algorithms. Algorithms 1.3 STACKS AND QUEUES. stacks resizing arrays queues generics iterators applications ROBERT SEDGEWICK KEVIN WAYNE. Algorithms ROBERT SEDGEWICK KEVIN WAYNE 1.3 STACKS AND QUEUES Algorithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE http://algs4.cs.princeton.edu stacks resizing arrays queues generics iterators

More information

Stacks and Queues. stacks dynamic resizing queues generics iterators applications. Stacks and queues

Stacks and Queues. stacks dynamic resizing queues generics iterators applications. Stacks and queues Stacks and queues Stacks and Queues stacks dynamic resizing queues generics iterars applications Fundamental data types. Values: sets of objects Operations: insert, remove, test if empty. Intent is clear

More information

4.3 Stacks and Queues

4.3 Stacks and Queues 4.3 Stacks and Queues Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 03/30/12 04:33:08 PM Data Types and Data Structures Data types.

More information

Stacks and Queues. !stacks!dynamic resizing!queues!generics!applications. Stacks and Queues

Stacks and Queues. !stacks!dynamic resizing!queues!generics!applications. Stacks and Queues Stacks and Queues Stacks and Queues!stacks!dynamic resizing!queues!generics!applications Fundamental data types. Values: sets of objects Operations: insert, remove, test if empty. Intent is clear when

More information

! Set of operations (add, remove, test if empty) on generic data. ! Intent is clear when we insert. ! Which item do we remove? Stack.

! Set of operations (add, remove, test if empty) on generic data. ! Intent is clear when we insert. ! Which item do we remove? Stack. Stacks and Queues 4.3 Stacks and Queues Fundamental data types.! Set of operations (add, remove, test if empty) on generic data.! Intent is clear when we insert.! Which item do we remove? Stack.! Remove

More information

4.3 Stacks and Queues. Stacks. Stacks and Queues. Stack API

4.3 Stacks and Queues. Stacks. Stacks and Queues. Stack API Stacks and Queues 4.3 Stacks and Queues Fundamental data types. Set of operations (add, remove, test if empty) on generic data. Intent is clear when we insert. Which item do we remove? Stack. Remove the

More information

TSP assignment next lecture

TSP assignment next lecture 3/18/12 Data Types and Data Structures CS 112 Introduction to Programming Data types. Set of values and operations on those values. Some are built into the Java language: int, double[], String, Most are

More information

2.6 Stacks and Queues

2.6 Stacks and Queues Stacks and Queues 2.6 Stacks and Queues Fundamental data types.! Set of operations (add, remove, test if empty) on generic data.! Intent is clear when we insert.! Which item do we remove? Stack.! Remove

More information

14. Stacks and Queues

14. Stacks and Queues Section 4.3 http://introcs.cs.princen.edu Data types and data structures Data types APIs Clients Strawman implementation Linked lists Implementations http://introcs.cs.princen.edu Set of values. Set of

More information

14. Stacks and Queues

14. Stacks and Queues 1 COMPUTER SCIENCE S E D G E W I C K / W A Y N E 14. Stacks and Queues Section 4.3 http://introcs.cs.princen.edu COMPUTER SCIENCE S E D G E W I C K / W A Y N E 14. Stacks and Queues APIs Clients Strawman

More information

14. Stacks and Queues

14. Stacks and Queues 1 COMPUTER SCIENCE S E D G E W I C K / W A Y N E 14. Stacks and Queues Section 4.3 http://introcs.cs.princen.edu COMPUTER SCIENCE S E D G E W I C K / W A Y N E 14. Stacks and Queues APIs Clients Strawman

More information

COMPUTER SCIENCE. Computer Science. 12. Stacks and Queues. Computer Science. An Interdisciplinary Approach. Section 4.3

COMPUTER SCIENCE. Computer Science. 12. Stacks and Queues. Computer Science. An Interdisciplinary Approach. Section 4.3 COMPUTER SCIENCE S E D G E W I C K / W A Y N E PA R T I I : A L G O R I T H M S, T H E O R Y, A N D M A C H I N E S Computer Science Computer Science An Interdisciplinary Approach Section 4.3 ROBERT SEDGEWICK

More information

CS2012 Programming Techniques II

CS2012 Programming Techniques II 27 January 14 Lecture 6 (continuing from 5) CS2012 Programming Techniques II Vasileios Koutavas 1 27 January 14 Lecture 6 (continuing from 5) 2 Previous Lecture Amortized running time cost of algorithms

More information

Week 4 Stacks & Queues

Week 4 Stacks & Queues CPSC 319 Week 4 Stacks & Queues Xiaoyang Liu xiaoyali@ucalgary.ca Stacks and Queues Fundamental data types. Value: collection of objects. Operations: insert, remove, iterate, test if empty. Intent is clear

More information

Basic Data Structures

Basic Data Structures Basic Data Structures Some Java Preliminaries Generics (aka parametrized types) is a Java mechanism that enables the implementation of collection ADTs that can store any type of data Stack s1

More information

Basic Data Structures 1 / 24

Basic Data Structures 1 / 24 Basic Data Structures 1 / 24 Outline 1 Some Java Preliminaries 2 Linked Lists 3 Bags 4 Queues 5 Stacks 6 Performance Characteristics 2 / 24 Some Java Preliminaries Generics (aka parametrized types) is

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

4.3 Stacks, Queues, and Linked Lists

4.3 Stacks, Queues, and Linked Lists 4.3 Stacks, Queues, and Linked Lists Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 3/21/2013 8:59:11 PM Data Types and Data Structures

More information

csci 210: Data Structures Stacks and Queues

csci 210: Data Structures Stacks and Queues csci 210: Data Structures Stacks and Queues 1 Summary Topics Stacks and Queues as abstract data types ( ADT) Implementations arrays linked lists Analysis and comparison Applications: searching with stacks

More information

CMSC 132, Object-Oriented Programming II Summer Lecture 9:

CMSC 132, Object-Oriented Programming II Summer Lecture 9: CMSC 132, Object-Oriented Programming II Summer 2018 Lecturer: Anwar Mamat Lecture 9: Disclaimer: These notes may be distributed outside this class only with the permission of the Instructor. 9.1 QUEUE

More information

CMSC 132: Object-Oriented Programming II. Stack and Queue

CMSC 132: Object-Oriented Programming II. Stack and Queue CMSC 132: Object-Oriented Programming II Stack and Queue 1 Stack Allows access to only the last item inserted. An item is inserted or removed from the stack from one end called the top of the stack. This

More information

Java generics. h"p:// h"p://

Java generics. hp://  hp:// Java generics h"p://www.flickr.com/photos/pdxdiver/4917853457/ h"p://www.flickr.com/photos/paj/4002324674/ CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014 Overview Abstract

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

Stacks and Queues. David Greenstein Monta Vista

Stacks and Queues. David Greenstein Monta Vista Stacks and Queues David Greenstein Monta Vista Stack vs Queue Stacks and queues are used for temporary storage, but in different situations Stacks are Used for handling nested structures: processing directories

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

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Abstract Data Type Stack Version of February 2, 2013 Abstract These lecture notes are meant

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Abstract Data Type Stack Version of February 2, 2013 Abstract These lecture notes are meant

More information

Building Java Programs

Building Java Programs Building Java Programs Appendix Q Lecture Q-1: stacks and queues reading: appendix Q 2 Runtime Efficiency (13.2) efficiency: measure of computing resources used by code. can be relative to speed (time),

More information

Abstract Data Types and Java Generics. Fundamentals of Computer Science

Abstract Data Types and Java Generics. Fundamentals of Computer Science Abstract Data Types and Java Generics Fundamentals of Computer Science Outline Abstract Data Types (ADTs) A collection of data and operations on that data Data Structure How we choose to implement an ADT

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

CSC 321: Data Structures. Fall 2012

CSC 321: Data Structures. Fall 2012 CSC 321: Data Structures Fall 2012 Lists, stacks & queues Collection classes: List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap, HashMap) ArrayList performance and implementation LinkedList

More information

Java generics. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

Java generics. CSCI 136: Fundamentals of Computer Science II Keith Vertanen Java generics h"p://www.flickr.com/photos/pdxdiver/4917853457/ h"p://www.flickr.com/photos/paj/4002324674/ CSCI 136: Fundamentals of Computer Science II Keith Vertanen Overview Abstract Data Types (ADTs)

More information

The Bucharest University of Economic Studies. Data Structures. ADTs-Abstract Data Types Stacks and Queues

The Bucharest University of Economic Studies. Data Structures. ADTs-Abstract Data Types Stacks and Queues The Bucharest University of Economic Studies Data Structures ADTs-Abstract Data Types Stacks and Queues Agenda Definition Graphical representation Internal interpretation Characteristics Operations Implementations

More information

Stacks and queues. CSCI 135: Fundamentals of Computer Science Keith Vertanen.

Stacks and queues. CSCI 135: Fundamentals of Computer Science Keith Vertanen. Stacks and queues http://www.flickr.com/photos/mac-ash/4534203626/ http://www.flickr.com/photos/thowi/182298390/ CSCI 135: Fundamentals of Computer Science Keith Vertanen Terminology Overview Abstract

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

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

-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

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

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

Midterm Exam (REGULAR SECTION)

Midterm Exam (REGULAR SECTION) Data Structures (CS 102), Professor Yap Fall 2014 Midterm Exam (REGULAR SECTION) October 28, 2014 Midterm Exam Instructions MY NAME:... MY NYU ID:... MY EMAIL:... Please read carefully: 0. Do all questions.

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

16-Dec-10. Collections & Data Structures ABSTRACTION VS. IMPLEMENTATION. Abstraction vs. Implementation

16-Dec-10. Collections & Data Structures ABSTRACTION VS. IMPLEMENTATION. Abstraction vs. Implementation Collections & Data Structures Boaz Kantor Introduction to Computer Science IDC Herzliya ABSTRACTION VS. IMPLEMENTATION 2 Abstraction vs. Implementation Data structures provide both abstraction and implementation.

More information

Advanced Java Concepts Unit 3: Stacks and Queues

Advanced Java Concepts Unit 3: Stacks and Queues Advanced Java Concepts Unit 3: Stacks and Queues Stacks are linear collections in which access is completely restricted to just one end, called the top. Stacks adhere to a last-in, first-out protocol (LIFO).

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

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 Goodrich, Tamassia, Goldwasser Stacks

Stacks Goodrich, Tamassia, Goldwasser Stacks Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Stacks Stacks 1 The Stack ADT The Stack ADT

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

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014 Lists CSC212 Lecture 8 D. Thiebaut, Fall 2014 Review List = Organization of Data in a Linear Fashion, where Order is Important Set of actions that can be carried out efficiently on the data. Typical Actions

More information

Name Section Number. CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

Name Section Number. CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice Name Section Number CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice All Sections Bob Wilson OPEN BOOK / OPEN NOTES You will have all 90 minutes until the start of the next class period. Spend

More information

Lecture 3 Linear Data Structures

Lecture 3 Linear Data Structures Lecture 3 Linear Data Structures - 1 - Learning Outcomes Based on this lecture, you should: Know the basic linear data structures Be able to express each as an Abstract Data Type (ADT) Be able to specify

More information

CSE Data Structures and Algorithms... In Java! Stacks. CSE2100 DS & Algorithms 1

CSE Data Structures and Algorithms... In Java! Stacks. CSE2100 DS & Algorithms 1 CSE 2100 Data Structures and Algorithms... In Java Stacks 1 What is Stack A stack is a collection of objects that are inserted and removed according to the last-in, first-out (LIFO) principle. Internet

More information

An Introduction to Data Structures

An Introduction to Data Structures An Introduction to Data Structures Advanced Programming ICOM 4015 Lecture 17 Reading: Java Concepts Chapter 20 Fall 2006 Adapded from Java Concepts Companion Slides 1 Chapter Goals To learn how to use

More information

Lecture 4 Stack and Queue

Lecture 4 Stack and Queue Lecture 4 Stack and Queue Bo Tang @ SUSTech, Spring 2018 Our Roadmap Stack Queue Stack vs. Queue 2 Stack A stack is a sequence in which: Items can be added and removed only at one end (the top) You can

More information

Queues Fall 2018 Margaret Reid-Miller

Queues Fall 2018 Margaret Reid-Miller Queues 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Writing methods various classes that implement Lists. Methods using Lists and Big-O w/ ArrayList or LinkedLists Prove

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

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

LIFO : Last In First Out

LIFO : Last In First Out Introduction Stack is an ordered list in which all insertions and deletions are made at one end, called the top. Stack is a data structure that is particularly useful in applications involving reversing.

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Cpt S 122 Data Structures. Course Review Midterm Exam # 1 Cpt S 122 Data Structures Course Review Midterm Exam # 1 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 1 When: Friday (09/28) 12:10-1pm Where:

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

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

Stacks and Queues. Fundamentals of Computer Science.

Stacks and Queues. Fundamentals of Computer Science. Stacks and Queues http://www.flickr.com/photos/mac-ash/4534203626/ http://www.flickr.com/photos/thowi/182298390/ Fundamentals of Computer Science Outline Terminology Abstract Data Types ADT) Data structures

More information

CS 211. Project 5 Infix Expression Evaluation

CS 211. Project 5 Infix Expression Evaluation CS 211 Project 5 Infix Expression Evaluation Part 1 Create you own Stack Class Need two stacks one stack of integers for the operands one stack of characters for the operators Do we need 2 Stack Classes?

More information

Implementing a Queue with a Linked List

Implementing a Queue with a Linked List CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 192] Implementing a Queue with a Linked List State representation: æ Data items are kept in a linked list. æ Pointer head points to

More information

CSE 143. Lecture 4: Stacks and Queues

CSE 143. Lecture 4: Stacks and Queues CSE 143 Lecture 4: Stacks and Queues Stacks and queues Sometimes it is good to have a collection that is less powerful, but is optimized to perform certain operations very quickly. Today we will examine

More information

[2:3] Linked Lists, Stacks, Queues

[2:3] Linked Lists, Stacks, Queues [2:3] Linked Lists, Stacks, Queues Helpful Knowledge CS308 Abstract data structures vs concrete data types CS250 Memory management (stack) Pointers CS230 Modular Arithmetic !!!!! There s a lot of slides,

More information

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle.

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle. Stacks 1 Stacks The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle. 2 Main stack operations Insertion and removal are defined by: push(e): inserts

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

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10 Keeping Order:! Stacks, Queues, & Deques 1 Stacks 2 Stacks A stack is a last in, first out (LIFO) data structure Primary Operations: push() add item to top pop() return the top item and remove it peek()

More information

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures 1.00 Lecture 26 Data Structures: Introduction Stacks Reading for next time: Big Java: 19.1-19.3 Data Structures Set of primitives used in algorithms, simulations, operating systems, applications to: Store

More information

infix expressions (review)

infix expressions (review) Outline infix, prefix, and postfix expressions queues queue interface queue applications queue implementation: array queue queue implementation: linked queue application of queues and stacks: data structure

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

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

Lecture 3 Linear Data Structures: Arrays, Array Lists, Stacks, Queues and Linked Lists

Lecture 3 Linear Data Structures: Arrays, Array Lists, Stacks, Queues and Linked Lists Lecture 3 Linear Data Structures: Arrays, Array Lists, Stacks, Queues and Linked Lists Chapters 3.1-3.3, 5.1-5.2, 6.1-1 - Core Collection Interfaces - 2 - The Java Collections Framework Interface Abstract

More information

Data Abstraction and Specification of ADTs

Data Abstraction and Specification of ADTs CITS2200 Data Structures and Algorithms Topic 4 Data Abstraction and Specification of ADTs Example The Reversal Problem and a non-adt solution Data abstraction Specifying ADTs Interfaces javadoc documentation

More information

Programming Abstractions

Programming Abstractions Programming Abstractions C S 1 0 6 B Cynthia Lee Today s Topics ADTs Stack Example: Reverse-Polish Notation calculator Queue Example: Mouse Events Stacks New ADT: Stack stack.h template

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

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

Adam Blank Lecture 5 Winter 2015 CSE 143. Computer Programming II

Adam Blank Lecture 5 Winter 2015 CSE 143. Computer Programming II Adam Blank Lecture 5 Winter 2015 CSE 143 Computer Programming II CSE 143: Computer Programming II Stacks & Queues Questions From Last Time 1 Can we include implementation details in the inside comments

More information

Algorithms and Data Structures

Algorithms and Data Structures Algorithms and Data Structures PD Dr. rer. nat. habil. Ralf Peter Mundani Computation in Engineering / BGU Scientific Computing in Computer Science / INF Summer Term 2018 Part 2: Data Structures PD Dr.

More information

PA3 Design Specification

PA3 Design Specification PA3 Teaching Data Structure 1. System Description The Data Structure Web application is written in JavaScript and HTML5. It has been divided into 9 pages: Singly linked page, Stack page, Postfix expression

More information

Stacks and Queues. Gregory D. Weber. CSCI C243 Data Structures

Stacks and Queues. Gregory D. Weber. CSCI C243 Data Structures Stacks and Queues Gregory D. Weber CSCI C243 Data Structures Principal Points 1. The Stack interface: how to declare it, what it does. 2. Generics: why they were added to Java, how to use them. 3. The

More information

#06 More Structures LIFO FIFO. Contents. Queue vs. Stack 3. Stack Operations. Pop. Push. Stack Queue Hash table

#06 More Structures LIFO FIFO. Contents. Queue vs. Stack 3. Stack Operations. Pop. Push. Stack Queue Hash table Contents #06 More Structures -07 FUNDAMENTAL PROGRAMMING I Stack Queue Hash table DEPARTMENT OF COMPUTER ENGINEERING, PSU v. Queue vs. Stack Stack Operations IN IN OUT Push: add an item to the top Pop:

More information

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Tools : The Java Compiler. The Java Interpreter. The Java Debugger Tools : The Java Compiler javac [ options ] filename.java... -depend: Causes recompilation of class files on which the source files given as command line arguments recursively depend. -O: Optimizes code,

More information

Lecture 3 Linear Data Structures

Lecture 3 Linear Data Structures Lecture 3 Linear Data Structures - 1 - Learning Outcomes Based on this lecture, you should: Know the basic linear data structures Be able to express each as an Abstract Data Type (ADT) Be able to specify

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

Stacks and Queues. Introduction to abstract data types (ADTs) Stack ADT. Queue ADT. Time permitting: additional Comparator example

Stacks and Queues. Introduction to abstract data types (ADTs) Stack ADT. Queue ADT. Time permitting: additional Comparator example Stacks and Queues Introduction to abstract data types (ADTs) Stack ADT applications interface for Java Stack ex use: reverse a sequence of values Queue ADT applications interface for Java Queue Time permitting:

More information

ADTs: Stacks and Queues

ADTs: Stacks and Queues Introduction to the Stack ADTs: Stack: a data structure that holds a collection of elements of the same type. - The elements are accessed according to LIFO order: last in, first out - No random access

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

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

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

Solution: The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion.

Solution: The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion. 1. What is the full form of LIFO? The full form of LIFO is Last In First Out. 2. Give some examples for stack application. The examples of stack application are reverse a string, post fix evaluation, infix

More information

Project 2 (Deques and Randomized Queues)

Project 2 (Deques and Randomized Queues) Project 2 (Deques and Randomized Queues) Prologue Project goal: implement generic and iterable data structures, such as double-ended and randomized queues, using arrays and linked lists Relevant lecture

More information

UNIT 6A Organizing Data: Lists Principles of Computing, Carnegie Mellon University

UNIT 6A Organizing Data: Lists Principles of Computing, Carnegie Mellon University UNIT 6A Organizing Data: Lists Carnegie Mellon University 1 Data Structure The organization of data is a very important issue for computation. A data structure is a way of storing data in a computer so

More information

CS 206 Introduction to Computer Science II

CS 206 Introduction to Computer Science II CS 206 Introduction to Computer Science II 07 / 26 / 2016 Instructor: Michael Eckmann Today s Topics Comments/Questions? Stacks and Queues Applications of both Priority Queues Michael Eckmann - Skidmore

More information

Linked List. April 2, 2007 Programming and Data Structure 1

Linked List. April 2, 2007 Programming and Data Structure 1 Linked List April 2, 2007 Programming and Data Structure 1 Introduction head A linked list is a data structure which can change during execution. Successive elements are connected by pointers. Last element

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information