11 12 stacks queue
TRANSCRIPT
-
7/31/2019 11 12 Stacks Queue
1/16
Fundamental Data Types: String, Math, Casting 1
Struktur Data & Algoritme(Data Structures & Algorithms)
Fa k u l t a s I l m u K o m p u t e r
Un i v e r s i t a s I n d o n e s i a
S em e s t e r Ge na p - 2 0 0 0 / 2 0 0 1V e r s i o n 1 .0 - I n t e r n a l U s e O n l y
Denny
Stacks & Queues
SDA/STACK-QUEUE/D N/V1.0/2
Reviewn Abstract data type (ADT)
n Kumpulan obyek dan metoda operasi yang
mempresentasikan sifat-sifat abstraks bagi "user"
dengan menyembunyikan bagaimana semua itu
direpresentasikan dalam representasi data level yang
lebih rendah
-
7/31/2019 11 12 Stacks Queue
2/16
Fundamental Data Types: String, Math, Casting 2
SDA/STACK-QUEUE/D N/V1.0/3
Objectives
n Memahami cara kerja dan kegunaan Stack & Queuen Dapat mengimplementasi stack dan queue
SDA/STACK-QUEUE/D N/V1.0/4
Outlinen ADT Stacks
n Basic operations
n Examples of use
n Implementations
Array-based and linked list-based
n ADT Queues
n Basic operations
n Examples of use
n Implementations
Array-based and linked list-based
-
7/31/2019 11 12 Stacks Queue
3/16
Fundamental Data Types: String, Math, Casting 3
SDA/STACK-QUEUE/D N/V1.0/5
Struktur data linear
n kumpulan komponen-komponen yang tersusunmembentuk satu garis linear
n Stack: struktur data linear dimana penambahan ataupengurangan komponen dilakukan di satu ujung saja.
n Queue: struktur data linear dimana penambahankomponen dilakukan di satu ujung, sementarapengurangan dilakukan di ujung lain (yang satu lagi).
n Kedua struktur tersebut merupakan struktur data
abstraks dimana implementasi pada tingkat lebihrendah dapat menggunakan struktur sikuensial (array)
atau struktur berkait (linear linked-list).
SDA/STACK-QUEUE/D N/V1.0/6
Stack
n All access is restricted to the most recently insertedelements
n Basic operations arepush,pop, top.
n Constant time basic operations
Stack
push pop, top
-
7/31/2019 11 12 Stacks Queue
4/16
Fundamental Data Types: String, Math, Casting 4
SDA/STACK-QUEUE/D N/V1.0/7
Non-Computer Examples
n Stack of papersn Stack of bills
n Stack of plates
n Expect O( 1 ) time per stack operation. (In otherwords, constant time per operation, no matter howmany items are actually in the stack).
SDA/STACK-QUEUE/D N/V1.0/8
Application
n Stack can be used to check a program for balancedsymbols (such as {}, (), []).
n Example: {()} is legal, {(}) is not (so simplycounting symbols does not work).
n When a closing symbol is seen, it matches the mostrecently seen unclosed opening symbol. Therefore, astack will be appropriate.
-
7/31/2019 11 12 Stacks Queue
5/16
Fundamental Data Types: String, Math, Casting 5
SDA/STACK-QUEUE/D N/V1.0/9
Balanced Symbol Algorithm
n Make an empty stack.n Repeatedly read tokens; if the token is
n an opening symbol, push it onto the stack
n a closing symbol
and the stack is empty, then report an error;
otherwise pop the stack and verify that the poppedsymbol is a match (if not report an error)
n At the end of the file, if the stack is not empty, reportan error.
SDA/STACK-QUEUE/D N/V1.0/10
Example
n Input: {()}
n Push {
n Push (; stack has {(
n Pop; popped item is ( which matches ). Stack nowhas {.
n Pop; popped item is { which matches }.
n End of file; stack is empty, so all is good.
-
7/31/2019 11 12 Stacks Queue
6/16
Fundamental Data Types: String, Math, Casting 6
SDA/STACK-QUEUE/D N/V1.0/11
Performance
n Running time is O( N), where Nis amount of data(that is, number of tokens).
n it processes the input sequentially, never needing tobacktrack.
SDA/STACK-QUEUE/D N/V1.0/12
Call Stack
n Matching symbols is similar to methodcall andmethod return, because when a method returns, itreturns to the most recently active method.
n Call stack can be used to keep track of this.
n Abstract idea: when method call is made, savecurrent state on a stack. On return, restore the stateby popping the stack.
-
7/31/2019 11 12 Stacks Queue
7/16
Fundamental Data Types: String, Math, Casting 7
SDA/STACK-QUEUE/D N/V1.0/13
Activation Records
n Actual implementation is slightly different (note thattext describes the abstract implementation).
n The top of stack can store the current methodenvironment.
n When method is called, the new enviromment ispushed onto stack.
n On return, old enviroment is restored by pop
SDA/STACK-QUEUE/D N/V1.0/14
Other Applications
n Recursion removal can be done with stacks
n Operator precedence parsing (future lecture)
n Reversing things is easily done with stacks
-
7/31/2019 11 12 Stacks Queue
8/16
Fundamental Data Types: String, Math, Casting 8
SDA/STACK-QUEUE/D N/V1.0/15
Array Implementations
n Stack can be implemented with an array and aninteger top that stores the array index of the top ofthe stack.
n Empty stack has top equal to -1.
n To push, increment the top counter, and write in thearray position.
n To pop, decrement the top counter.
SDA/STACK-QUEUE/D N/V1.0/16
Stages
top(-1)
A top(0) A
B top(1)
-
7/31/2019 11 12 Stacks Queue
9/16
Fundamental Data Types: String, Math, Casting 9
SDA/STACK-QUEUE/D N/V1.0/17
Array Doubling
n If stack is full (because array size has been reached),we can extend the array, using array doubling.
n We allocate a new, double-sized array and copycontents over:
Object [] oldArray = array;
array = new Object [oldArray.length * 2 ];
for (int j = 0; j < oldArray.length; j++)
array[j] = oldArray[j];
n Amortization technique
SDA/STACK-QUEUE/D N/V1.0/18
Running Time
n Without array doubling, all operations are constanttime, and do not depend on number of items in thestack.
n With array, doubling, a push could occasionally beO(N). However, it is essentially O(1) because eacharray doubling that costs Nassignments is precededby N/2 non-doubling pushes.
-
7/31/2019 11 12 Stacks Queue
10/16
Fundamental Data Types: String, Math, Casting 10
SDA/STACK-QUEUE/D N/V1.0/19
Linked-List Implementation
n first item in the list = top of stackn push:
n create a new node
n attach it as the new first element
n pop:
n advance tos to the second item in the list
d c b a
topOfStack
SDA/STACK-QUEUE/D N/V1.0/20
Queues
n All access is restricted to the least recently insertedelements
n Basic operations are enqueue, dequeue, getFront.
n Constant time basic operations
Queueenqueuedequeue
getFront
-
7/31/2019 11 12 Stacks Queue
11/16
Fundamental Data Types: String, Math, Casting 11
SDA/STACK-QUEUE/D N/V1.0/21
Examples
n Line for 21 ticketsn Line printer queue
n Queue is a British word for line.
n Expect O(1) time per queue operation because it issimilar to stack.
SDA/STACK-QUEUE/D N/V1.0/22
Applications
n Queues are useful for storing pending work.
n We will see several examples later in the course:
n Shortest paths problem (minimize the number ofconnecting flights between two arbitrary airports)
n Topological ordering: given a sequence ofevents, andpairs (a,b) indicating that event aMUST occur prior tob, provide a schedule.
-
7/31/2019 11 12 Stacks Queue
12/16
Fundamental Data Types: String, Math, Casting 12
SDA/STACK-QUEUE/D N/V1.0/23
Queues: Simple Idea
n Store items in an array with front item at index zeroand back item at index Back.
n Enqueue is easy: increment Back.
n Dequeue is inefficient: all elements have to beshifted.
n Result: Dequeue will be O( N).
SDA/STACK-QUEUE/D N/V1.0/24
Better Idea
n Keep a Front index.
n To Dequeue, increment Front.
a b c d
Front Back
a b c d
Front Back
-
7/31/2019 11 12 Stacks Queue
13/16
Fundamental Data Types: String, Math, Casting 13
SDA/STACK-QUEUE/D N/V1.0/25
Circular Implementation
n Previous implementation is O(1) per operation.n However, afterArray.length enqueues, we are full,
even if queue is logically nearly empty.
n Solution: use wraparound to reuse the cells at thestart of the array. To increment, add one, but if thatgoes past end, reset to zero.
SDA/STACK-QUEUE/D N/V1.0/26
Circular Example
n Both Front and Back wraparound as needed.
b c d
Front Back
b c d
FrontBack
e f
e fg
-
7/31/2019 11 12 Stacks Queue
14/16
Fundamental Data Types: String, Math, Casting 14
SDA/STACK-QUEUE/D N/V1.0/27
Java Implementation
n Mostly straightforward; maintainn Front
n Rear
n Current number of items in queue
n Only tricky part is array doubling because contiguityof wraparound must be maintained.
SDA/STACK-QUEUE/D N/V1.0/28
Linked-List Application
n front back
n enqueue:
n create a new node
n if empty, front = back
n else attach it as the new back
n dequeue:
n get node at the front
a b c d
front back
-
7/31/2019 11 12 Stacks Queue
15/16
Fundamental Data Types: String, Math, Casting 15
SDA/STACK-QUEUE/D N/V1.0/29
Summary
n Both the array and linked-list versions run in O(1)n Linked-list has overhead one reference each node
n Especially for Queues, array-based implementation isharder to code
n Doubling space in array implementation need at leastthree times as much as the number of data items.
SDA/STACK-QUEUE/D N/V1.0/30
Further Readingn Chapter 6, 15
-
7/31/2019 11 12 Stacks Queue
16/16
Fundamental Data Types: String, Math, Casting 16
SDA/STACK-QUEUE/D N/V1.0/31
Whats Next
n Application of stack & queue, orn Tree