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 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 when we add. Which item do we remove? Algithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE stacks resizing arrays queues generics iterars applications stack queue enqueue Stack. Examine the item. push pop dequeue LIFO = "last in out" Queue. Examine the item. FIFO = " in out" Last updated on Feb 9, 2015, 5:18 AM 2 Client, implementation, interface Separate interface and implementation. Ex: stack, queue, bag, priity queue, symbol table, union-find,. Benefits. Client cannot know details of implementation client has many implementation from which choose. Implementation cannot know details of client needs many clients can re-use the same implementation. Design: creates modular, reusable libraries. Perfmance: substitute optimized implementation when it matters. Client: program using operations defined in interface. Implementation: actual code implementing operations. Interface: description of data type, basic operations. Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications 3

2 Stack API Stacks quiz 1 Warmup API. Stack of strings data type. How implement a stack with a singly-linked list? public class StackOfStrings push pop A. StackOfStrings() create an empty stack it was the st of void push(string item) add a new string stack String pop() remove and return the string B. boolean isempty() is the stack empty? int size() numr of strings on the stack of st the was it C. None of the above. Warmup client. Reverse sequence of strings from standard input. 5 D. I don't know. 6 Stack: linked-list implementation Maintain pointer node in a singly-linked list. Push new item fe. Pop item from. Stack pop: linked-list implementation save item return String item =.item; delete node inner class =.next; String item; Node next; of st the was it 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 private String item; private Node next; private inner class (access modifiers f instance variables don't matter) inner class String item; Node next; 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 = "not";.next = old; not String item =.item; =.next; 9 10 Stack: linked-list implementation perfmance Stacks quiz 2 Proposition. Every operation takes constant time in the wst case. How implement a fixed-capacity stack with an array? Proposition. A stack with N items uses ~ 40 N bytes. A. it was the st of times inner class object overhead 16 bytes (object overhead) String item; Node next; extra overhead item next references 8 bytes (inner class extra overhead) 8 bytes (reference String) 8 bytes (reference Node) B. times of st the was it 40 bytes allocated per stack node Remark. This accounts f the memy f the stack C. None of the above. (but not memy f the strings themselves, which the client owns). D. I don't know

4 Fixed-capacity stack: array implementation Use array s[] sre N items on stack. push(): add new item at s[n]. pop(): remove item from s[n-1]. Fixed-capacity stack: array implementation public class FixedCapacityStackOfStrings private String[] s; private int N = 0; a cheat (stay tuned) public FixedCapacityStackOfStrings(int capacity) s = new String[capacity]; s[] it was the st of times N capacity = 10 return N == 0; public void push(string item) s[n++] = item; use index in array; then increment N return s[--n]; Defect. Stack overflows when N exceeds capacity. [stay tuned] decrement N; then use index in array Stack considerations 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 added. Duplicate items. We allow an item added me than once. Loitering. Holding a reference an object when it is no longer needed. return s[--n]; loitering String item = s[--n]; s[n] = ; this version avoids "loitering": garbage collecr can reclaim memy f an object only if no remaining references Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications 15

5 Stack: resizing-array implementation Stack: resizing-array implementation Problem. Requiring client provide capacity does not implement API! Q. How grow array? "repeated doubling" Q. How grow and shrink array? A. If array is full, create a new array of twice the size, and copy items. First try. push(): increase size of array s[] by 1. pop(): decrease size of array s[] by 1. Too expensive. infeasible f large N Need copy all items a new array, f each operation. Array accesses add N items = N + ( (N 1)) ~ N 2. 1 array access per push 2(k 1) array accesses expand size k (igning cost create new array) public ResizingArrayStackOfStrings() s = new String[1]; 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; Array accesses add N = 2 i items. N + ( N) ~ 3N. Challenge. Ensure that array resizing happens infrequently array access per push k array accesses double size k (igning cost create new array) 18 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. Efficient solution. push(): double size of array s[] when array is full. pop(): halve size of array s[] when array is one-quarter full. Too expensive in wst case. Consider push-pop-push-pop- sequence when array is full. Each operation takes time proptional N. full not String item = s[--n]; s[n] = ; if (N > 0 && N == s.length/4) resize(s.length/2); push("") not pop() not push("") not Invariant. Array is tween 25% and 100% full

6 Stack resizing-array implementation: perfmance Stack resizing-array implementation: memy usage Amtized analysis. Starting from an empty data structure, 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. Proposition. A ResizingArrayStackOfStrings uses ~ 8 N ~ 32 N bytes of memy f a stack with N items. ~ 8 N when full. ~ 32 N when one-quarter full. construct push typical wst amtized N 1 public class ResizingArrayStackOfStrings private String[] s; private int N = 0; 8 bytes array size pop size 1 N doubling and halving operations der of growth of running time f resizing array stack with N items Remark. This accounts f the memy f the stack (but not the memy f strings themselves, which the client owns) Stack implementations: resizing array vs. linked list 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 not Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications not 23

7 Queue API Queues quiz 1 enqueue How implement a queue with a singly-linked linked list? public class QueueOfStrings A. QueueOfStrings() create an empty queue times of st the was it void enqueue(string item) add a new string queue String dequeue() remove and return the string boolean isempty() is the queue empty? int size() numr of strings on the queue B. it was the st of times dequeue C. None of the above. 25 D. I don't know. 26 Queue: linked-list implementation Maintain one pointer node in a singly-linked list. Maintain another pointer last last node. Dequeue from. Enqueue after last. Queue dequeue: linked-list implementation save item return String item =.item; delete node =.next; inner class String item; Node next; last last it was the st of times last 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 LinkedStackOfStrings */ return == ; inner class String item; Node next; create a new node f the end last = new Node(); last.item = "not"; link the new node the end of the list oldlast.next = last; oldlast oldlast last last not not 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 Queues quiz 2 How implement a fixed-capacity queue with an array? A. it was the st of times Queue: resizing-array implementation Use array q[] sre items in queue. enqueue(): add new item at q[tail]. dequeue(): remove item from q[head]. Update head and tail modulo the capacity. Add resizing array. B. times of st the was it q[] the st of times head tail capacity = 10 C. None of the above. D. I don't know. Q. How resize? 31 32

9 QUEUE WITH TWO STACKS Problem. Implement a queue with two stacks so that: Each queue op uses a constant amtized numr of stack ops. At most constant extra memy (sides two stacks). 1.3 B AGS, QUEUES, AND S TACKS Applications. Job interview. Implement an immutable persistent queue. Implement a queue in a (purely) functional programming language. stacks resizing arrays queues Algithms generics iterars R OBERT S EDGEWICK K EVIN W AYNE applications 33 Parameterized stack Generic stack: linked-list implementation We implemented: StackOfStrings. public class LinkedStackOfStrings private Node = ; We also want: StackOfURLs, StackOfInts, StackOfApples, StackOfOranges,. String item; Node next; Solution in Java: generics. return == ; type parameter (use both specify type and call construcr) Stack<Apple> stack = new Stack<Apple>(); Apple apple = new Apple(); Orange ange = new Orange(); stack.push(apple); stack.push(ange); public class Stack<Item> private Node = ; compile-time err Item item; Node next; 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; 36

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 not 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]; ^ Q. Why does Java make me cast ( use reflection)? Sht answer. Backward compatibility. Long answer. Need learn about type erasure and covariant arrays. 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> stack = new Stack<Integer>(); stack.push(17); int a = stack.pop(); // stack.push(integer.valueof(17)); // int a = stack.pop().intvalue(); Botm line. Client code can use generic stack f any type of data

11 Stacks quiz 5 Which of the following is the crect way declare and initialize an empty stack of characters? A. Stack<Character> stack = new Stack(); 1.3 BAGS, QUEUES, AND STACKS B. Stack stack = new Stack<Character>(); C. Stack<Character> stack = new Stack<Character>(); D. Stack<char> stack = new Stack<char>(); Algithms ROBERT SEDGEWICK KEVIN WAYNE stacks resizing arrays queues generics iterars applications see precept E. None of the above. 41 Iteration Feach loop Design challenge. Suppt iteration over stack items by client, without revealing the internal representation of the stack. Java provides elegant syntax f iteration over collections. feach loop (shthand) equivalent code (longhand) resizing-array representation i N Stack<String> stack;... Stack<String> stack;... s[] it was the st of times linked-list representation current f (String s : stack)... Iterar<String> i = stack.iterar(); while (i.hasnext()) String s = i.next();... times of st the was it Java solution. Use a feach loop. To make user-defined collection suppt feach loop: Data type must have a method named iterar(). The iterar() method returns an object that has two ce method. the hasnext() methods returns false when there are no me items the next() method returns the next item in the collection 43 44

12 Iterars Stack iterar: linked-list implementation To suppt feach loops, Java provides two interfaces. Iterar interface: next() and hasnext() methods. Iterable interface: iterar() method that returns an Iterar. Both should used with generics. java.util.iterar interface public interface Iterar<Item> boolean hasnext(); Item next(); optional; use void remove(); at your own risk Type safety. java.lang.iterable interface public interface Iterable<Item> Iterar<Item> iterar(); iterar(); Data type must use these interfaces suppt feach loop. Client program won't compile if implementation doesn't. 45 impt java.util.iterar; public class Stack<Item> implements Iterable<Item>... public Iterar<Item> iterar() return new ListIterar(); private class ListIterar implements Iterar<Item> private Node current = ; public boolean hasnext() return current!= ; public void remove() /* not 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 46 Stack iterar: array implementation Bag API impt java.util.iterar; public class Stack<Item> implements Iterable<Item>... public Iterar<Item> iterar() return new ReverseArrayIterar(); private class ReverseArrayIterar implements Iterar<Item> private int i = N; public boolean hasnext() return i > 0; public void remove() /* not suppted */ public Item next() return s[--i]; Main application. Adding items a collection and iterating (when der doesn't matter). public class Bag<Item> implements Iterable<Item> Bag() create an empty bag void add(item x) add a new item bag int size() numr of items in bag Iterar<Item> iterar() iterar f all items in bag a bag of marbles add( ) add( ) f (Marble m : bag) i N process each marble m (in any der) s[] it was the st of times 47 Implementation. Stack (without pop) queue (without dequeue). 48

13 Java collections library List interface. java.util.list is API f a sequence of items. Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications public interface List<Item> extends Iterable<Item> List() create an empty list boolean isempty() is the list empty? int size() numr of items void add(item item) add 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? Iterar<Item> iterar() iterar over all items in the list Implementations. java.util.arraylist uses a resizing array; java.util.linkedlist uses doubly-linked list. Caveat: only some operations are efficient. 50 Java collections library Java collections library java.util.stack. Suppts push(), pop(), and iteration. Inherits from java.util.vecr, which implements java.util.list interface. java.util.stack. Suppts push(), pop(), and iteration. Inherits from java.util.vecr, which implements java.util.list interface. 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. java.util.queue. An interface, not an implementation of a queue. status (closed, will not fix) Best practices. Use our implementations of Stack and Queue. It was an increct design decision have Stack extend Vecr ("is-a" rather than "has-a"). We sympathize with the submitter but cannot fix this cause of compatibility

14 War sry (from Assignment 1) Generate random open sites in an N-by-N percolation system. Jenny: pick (i, j) at random; if already open, repeat. Takes ~ c1 N 2 seconds. Kenny: create a java.util.arraylist of N 2 closed sites. Pick an index at random and delete. Takes ~ c2 N 4 seconds. Why is my program so slow? Stack applications 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.... Kenny Lesson. Don't use a library until you understand its API! This course. Cannot use a library until we've implemented it in class 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. Goal. Evaluate infix expressions. ( 1 + ( ( ) * ( 4 * 5 ) ) ) value stack operar stack ( 1 + ( ( ) * ( 4 * 5 ) ) ) + ( ( ) * ( 4 * 5 ) ) ) ( ( ) * ( 4 * 5 ) ) ) Recursive function. Function that calls itself. Note. Can always use an explicit stack remove recursion. operand operar ) * ( 4 * 5 ) ) ) 3 ) * ( 4 * 5 ) ) ) 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); Two-stack algithm. [E. W. Dijkstra] Value: push on the value stack. Operar: push on the operar stack. 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! * * * * * * * ) * ( 4 * 5 ) ) ) * ( 4 * 5 ) ) ) ( 4 * 5 ) ) ) * 5 ) ) ) 5 ) ) ) ) ) ) ) ) ) 55 56

15 Dijkstra's two-stack algithm demo Arithmetic expression evaluation infix expression value stack operar stack (fully parenthesized) ( 1 + ( ( ) * ( 4 * 5 ) ) ) operand operar 57 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("(")) /* noop */ ; 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 ) ) ) Crectness Stack-based programming languages Q. Why crect? Observation 1. Dijkstra's two-stack algithm computes the same value if A. When algithm encounters an operar surrounded by two values the operar occurs after the two values. within parentheses, it leaves the result on the value stack. ( 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" notation. Applications. Postscript, Fth, calculars, Java virtual machine, 59 60

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. 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 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

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

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

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

! 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

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

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

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 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

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 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

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

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

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

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

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

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

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

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

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, 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. 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

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

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

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

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

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

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

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

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

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

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

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

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

1 P age DS & OOPS / UNIT II

1 P age DS & OOPS / UNIT II UNIT II Stacks: Definition operations - applications of stack. Queues: Definition - operations Priority queues - De que Applications of queue. Linked List: Singly Linked List, Doubly Linked List, Circular

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

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

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

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

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

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

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

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

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

Queues. Stacks and Queues

Queues. Stacks and Queues Queues Reading: RS Chapter 14 Slides are modified from those provided by Marty Stepp www.buildingjavaprograms.com 1 Stacks and Queues Sometimes a less powerful, but highly optimized collection is useful.

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

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

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50 Lists, Stacks, and Queues (Lists, Stacks, and Queues ) Data Structures and Programming Spring 2016 1 / 50 Abstract Data Types (ADT) Data type a set of objects + a set of operations Example: integer set

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 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

[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. 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

List, Stack, and Queues

List, Stack, and Queues List, Stack, and Queues R. J. Renka Department of Computer Science & Engineering University of North Texas 02/24/2010 3.1 Abstract Data Type An Abstract Data Type (ADT) is a set of objects with a set of

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

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

COS 226 Algorithms and Data Structures Fall Midterm

COS 226 Algorithms and Data Structures Fall Midterm COS 226 Algorithms and Data Structures Fall 2017 Midterm This exam has 10 questions (including question 0) worth a total of 55 points. You have 0 minutes. This exam is preprocessed by a computer, so please

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

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

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures MIDTERM EXAMINATION Spring 2010 CS301- Data Structures Question No: 1 Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the

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

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

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

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

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

CSC 321: Data Structures. Fall 2013

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

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

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR STUDENT IDENTIFICATION NO MULTIMEDIA COLLEGE JALAN GURNEY KIRI 54100 KUALA LUMPUR FIFTH SEMESTER FINAL EXAMINATION, 2014/2015 SESSION PSD2023 ALGORITHM & DATA STRUCTURE DSEW-E-F-2/13 25 MAY 2015 9.00 AM

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

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

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

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

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

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

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

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

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

DATA STRUCUTRES. A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.

DATA STRUCUTRES. A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently. DATA STRUCUTRES A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently. An algorithm, which is a finite sequence of instructions, each of which

More information

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES CH4.2-4.3. ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

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

Week 6. Data structures

Week 6. Data structures 1 2 3 4 5 n Week 6 Data structures 6 7 n 8 General remarks We start considering Part III Data Structures from CLRS. As a first example we consider two special of buffers, namely stacks and queues. Reading

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

Information Science 2

Information Science 2 Information Science 2 - Basic Data Structures- Week 02 College of Information Science and Engineering Ritsumeikan University Today s class outline l Basic data structures: Definitions and implementation

More information

Summer Final Exam Review Session August 5, 2009

Summer Final Exam Review Session August 5, 2009 15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

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

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

4.3: Linked Structures

4.3: Linked Structures Linked vs. Sequential Allocation 4.3: Linked Structures "The name of the song is called 'Haddocks' Eyes.' " "Oh, that's the name of the song, is it?" Alice said, trying to feel interested. "No, you don't

More information

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples: Ch. 8: ADTs: Stacks and Queues Abstract Data Type A data type for which: CS 8 Fall Jill Seaman - only the properties of the data and the operations to be performed on the data are specific, - not concerned

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

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 2018 Topic Notes: Linear Structures The structures we ve seen so far, Vectors/ArrayLists and linked list variations, allow insertion and deletion

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

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

Linear Data Structures

Linear Data Structures Linear Data Structures Arrays Arrays are stored in contiguous memory locations and contain similar data An element can be accessed, inserted or removed by specifying its position (number of elements preceding

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

Computer Science First Exams Pseudocode Standard Data Structures Examples of Pseudocode

Computer Science First Exams Pseudocode Standard Data Structures Examples of Pseudocode Computer Science First Exams 2014 Pseudocode Standard Data Structures Examples of Pseudocode Candidates are NOT permitted to bring copies of this document to their examinations. 1 Introduction The purpose

More information