Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stacks and Queues DSA 2013 Stacks n Queues.

Similar presentations


Presentation on theme: "Stacks and Queues DSA 2013 Stacks n Queues."— Presentation transcript:

1 Stacks and Queues DSA 2013 Stacks n Queues

2 A Different Kind of Structure
There are significant differences between the data structures and algorithms of Arrays and that for Stacks & Queues. We’ll discuss three differences: Programmer’s Tools Arrays—as well as many other structures (linked lists, trees, etc.) are appropriate for the kind of data you might find in a database application. They’re typically used for personnel records, inventories, financial data, etc.—data that corresponds to real-world objects or activities. These structures facilitate access to data: they make it easy to insert, delete, and search for particular items. DSA 2013 Stacks n Queues

3 A Different Kind of Structure
Stacks and Queues, on the other hand, are more often used as programmer’s tools. They’re primarily conceptual aids rather than full-fledged data storage devices. Their lifetime is typically shorter than that of the database-type structures. They are created and used to carry out a particular task during the operation of a program; when the task is completed, they’re discarded. DSA 2013 Stacks n Queues

4 A Different Kind of Structure
Restricted Access In an array, any item can be accessed, either immediately—if its index number is known—or by searching through a sequence of cells until it’s found. In Stacks and Queues, however, access is restricted: Only one item can be read or removed at a given time. More Abstract Stacks and queues are more abstract entities than arrays and many other data storage structures. The underlying mechanism used to implement them is typically not visible to their user. The underlying mechanism for a stack, for example, can be an array or a linked list. The underlying mechanism for a priority queue can be an array or a special kind of tree called a heap. DSA 2013 Stacks n Queues

5 Stacks DSA 2013 Stacks n Queues

6 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 conditions associated with operations DSA 2013 Stacks n Queues

7 Abstract Data Types (ADTs)
Example: ADT modeling a simple stock trading system The data stored are buy/sell orders The operations supported are order buy(stock, shares, price) order sell(stock, shares, price) void cancel(order) Error conditions: Buy/sell a nonexistent stock Cancel a nonexistent order DSA 2013 Stacks n Queues

8 The Stack ADT A stack is a list with the restriction
that insertions and deletions can only be performed at the top of the list Stacks are less flexible but are more efficient and easy to implement Stacks are known as LIFO (Last In, First Out) lists. Insertions and deletions follow the last-in first-out scheme The last element inserted will be the first to be retrieved DSA 2013 Stacks n Queues

9 The Stack ADT Think of a spring-loaded plate dispenser
Main stack operations: Push: inserts an element to the top of the stack Pop: removes and returns the last inserted element Auxiliary stack operations: Top: returns the last inserted element without removing it integer Size: returns the number of elements stored boolean isEmpty: indicates whether no elements are stored DSA 2013 Stacks n Queues

10 Stack Stack top DSA 2013 Stacks n Queues

11 THE CONCEPT OF STACK Consider this stack: values are stored and retrieved in "last in first out" manner by using operations push and pop. DSA 2013 Stacks n Queues

12 Exceptions Attempting the execution of an operation may sometimes cause an error condition, called an exception Exceptions are said to be “thrown” by an operation that cannot be executed In the Stack ADT, operations pop and top cannot be performed if the stack is empty Attempting the execution of pop or top on an empty stack throws an EmptyStackException DSA 2013 Stacks n Queues

13 Applications of Stacks
Direct applications Page-visited history in a Web browser Undo sequence in a text editor Chain of Method calls in the Java Virtual Machine DSA 2013 Stacks n Queues

14 Method Stack in the JVM The Java Virtual Machine (JVM) keeps track of the chain of active methods with a stack When a method is called, the JVM pushes on the stack a frame containing Local variables and return value Program counter, keeping track of the statement being executed When a method ends, its frame is popped from the stack and control is passed to the method on top of the stack main() { int i = 5; foo(i); } foo(int j) { int k; k = j+1; bar(k); } bar(int m) { … } bar PC = 1 m = 6 foo PC = 3 j = 5 k = 6 main PC = 2 i = 5 DSA 2013 Stacks n Queues

15 Implementation of Stacks
need an underlying collection to hold the elements of the stack 2 basic choices Arrays (static: the size of stack is given initially) Linked lists (dynamic: never become full) DSA 2013 Stacks n Queues

16 Array Implementation of Stack
A simple way of implementing the Stack ADT uses an array Need to declare an array size ahead of time A variable keeps track of the index of the top element, say, TopOfStack for an empty stack, set TopOfStack to -1 Push (1)   Increment TopOfStack by 1. (2)   Set Stack[TopOfStack] = X Pop (1)   Set return value to Stack[TopOfStack] (2)   Decrement TopOfStack by 1 These operations are performed in very fast constant time DSA 2013 Stacks n Queues

17 Array-based Stack Algorithm size() For Stack S and TopofStack t :
return t + 1 Algorithm pop() if isEmpty() then throw EmptyStackException else t  t  1 return S[t + 1] For Stack S and TopofStack t : S 1 2 t DSA 2013 Stacks n Queues

18 Array-based Stack (cont.)
The array storing the stack elements may become full A push operation will then throw a FullStackException Limitation of the array-based implementation Not built-in to the Stack ADT Algorithm push(o) if t = S.length  1 then throw FullStackException else t  t + 1 S[t]  o S 1 2 t DSA 2013 Stacks n Queues

19 Performance and Limitations
Let n be the number of elements in the stack The space used is O(n) Each operation runs in constant time O(1) That is, the time is not dependent on how many items are in the stack and is therefore very quick. No comparisons or moves are necessary. Limitations The maximum size of the stack must be defined ahead of time and cannot be changed Trying to push a new element into a full stack causes an implementation-specific exception DSA 2013 Stacks n Queues

20 Parentheses Matching In processing programs and working with computer languages there are many instances when symbols must be balanced Each “(”, “{”, or “[” must be paired with a matching “)”, “}”, or “[” correct: ( )(( )){([( )])} correct: ((( )(( )){([( )])} incorrect: )(( )){([( )])} incorrect: ({[ ])} A stack is useful for checking symbol balance. When a closing symbol is found it must match the most recent opening symbol of the same type. Algorithm? DSA 2013 Stacks n Queues

21 Algorithm for Balanced Symbol Checking
Make an empty stack read symbols until end of file if the symbol is an opening symbol push it onto the stack if it is a closing symbol do the following if the stack is empty report an error otherwise pop the stack. If the symbol popped does not match the closing symbol report an error At the end of the file if the stack is not empty report an error DSA 2013 Stacks n Queues

22 Parentheses Matching Algorithm
Algorithm ParenMatch(X,n): Input: An array X of n tokens, each of which is either a grouping symbol, a variable, an arithmetic operator, or a number Output: true if and only if all the grouping symbols in X match Let S be an empty stack for i=0 to n-1 do if X[i] is an opening grouping symbol then S.push(X[i]) else if X[i] is a closing grouping symbol then if S.isEmpty() then return false {nothing to match with} if S.pop() does not match the type of X[i] then return false {wrong type} return true {every symbol matched} else return false {some symbols were never matched} DSA 2013 Stacks n Queues

23 Queues DSA 2013 Stacks n Queues

24 Queue ADT Like a stack, a queue is also a list.
However, with a queue, insertion is done at one end, while deletion is performed at the other end. Accessing the elements of queues follows a First In, First Out (FIFO) order. the first element added to the queue will be the first one to be removed Like customers standing in a check-out line in a store, the first customer in is the first customer served.(or at a Bank) Add items to the back (rear) of the queue Access and remove from the front Used extensively in operating systems Queues of processes, I/O requests, and much more DSA 2013 Stacks n Queues

25 Enqueue and Dequeue Basic operations:
Enqueue: insert an element at the rear of the list Dequeue: remove the element at the front of the list Remove (Dequeue) Insert (Enqueue) front rear DSA 2013 Stacks n Queues

26 Queue Example Operation Output Q enqueue(5) – (5) enqueue(3) – (5, 3)
dequeue() 5 (3) enqueue(7) – (3, 7) dequeue() 3 (7) front() 7 (7) dequeue() 7 () dequeue() “error” () isEmpty() true () enqueue(9) – (9) enqueue(7) – (9, 7) size() 2 (9, 7) enqueue(3) – (9, 7, 3) enqueue(5) – (9, 7, 3, 5) dequeue() 9 (7, 3, 5) DSA 2013 Stacks n Queues

27 Applications of Queues
Direct applications Waiting lists, bureaucracy Access to shared resources (e.g., printer) Multiprogramming DSA 2013 Stacks n Queues

28 Implementation of Queue
Just as stacks can be implemented as arrays or linked lists, so with queues. Dynamic queues have the same advantages over static queues as dynamic stacks have over static stacks DSA 2013 Stacks n Queues

29 Queue Implementation of Array
There are several different algorithms to implement Enqueue and Dequeue Naïve way When enqueuing, the front index is always fixed and the rear index moves forward in the array. rear rear rear 3 3 6 3 6 9 front front front Enqueue(3) Enqueue(6) Enqueue(9) DSA 2013 Stacks n Queues

30 Queue Implementation of Array
Naïve way When dequeuing, the element at the front the queue is removed. If the front index is always fixed, then we have to move all the elements after it by one position. (Inefficient!!!) rear rear rear = -1 6 9 9 front front front Dequeue() Dequeue() Dequeue() DSA 2013 Stacks n Queues

31 Queue Implementation of Array
Better way Instead, we keep the items in the same place and move the front and rear of the queue. XXXXOOOOO (rear) OXXXXOOOO (after 1 dequeue, and 1 enqueue) OOXXXXXOO (after 2 dequeues, and 3 enqueues) OOOOXXXXX (after 4 dequeues, and 5 enqueues) The trouble with this arrangement is that soon the rear of the queue is at the end of the array (the highest index). (front) DSA 2013 Stacks n Queues

32 A Circular Queue Even if there are empty cells at the beginning of the array, because you’ve removed them , you still can’t insert a new item because Rear can’t go any further. Wrapping around To avoid the problem of not being able to insert more items into the queue even when it’s not full, the Front and Rear arrows wrap around to the beginning of the array. The result is a circular queue DSA 2013 Stacks n Queues

33 Implementation using Circular Array
Using a circular array When an element moves past the end of a circular array, it wraps around to the beginning, e.g. OOOOO7963  4OOOO7963 (after Enqueue(4)) After Enqueue(4), the rear index moves from pointing to 3 and points to 4. DSA 2013 Stacks n Queues

34 DSA 2013 Stacks n Queues

35 Implementation Array-based Queue
Use an array of size N in a circular fashion Two variables keep track of the front and rear f index of the front element r index immediately past the rear element Array location r is kept empty normal configuration Q 1 2 r f wrapped-around configuration Q 1 2 f r DSA 2013 Stacks n Queues

36 Queue Operations We use the modulo operator (remainder of division)
Algorithm size() return (N - f + r) mod N Algorithm isEmpty() return (f = r) Q 1 2 r f Q 1 2 f r DSA 2013 Stacks n Queues

37 Queue Operations (cont.)
Algorithm enqueue(o) if size() = N  1 then throw FullQueueException else Q[r]  o r  (r + 1) mod N Operation enqueue throws an exception if the array is full This exception is implementation-dependent Q 1 2 r f Q 1 2 f r DSA 2013 Stacks n Queues

38 Queue Operations (cont.)
Algorithm dequeue() if isEmpty() then throw EmptyQueueException else o  Q[f] f  (f + 1) mod N return o Operation dequeue throws an exception if the queue is empty This exception is specified in the queue ADT Q 1 2 r f Q 1 2 f r DSA 2013 Stacks n Queues

39 Deques A deque is a double-ended queue.
You can insert items at either end and delete them from either end. The methods might be called insertLeft() and insertRight(), and removeLeft() and removeRight(). If you restrict yourself to insertLeft() and removeLeft() (or their equivalents on the right), the deque acts like a stack. If you restrict yourself to insertLeft() and removeRight() (or the opposite pair), it acts like a queue. A deque provides a more versatile data structure than either a stack or a queue. However, it’s not used as often as stacks and queues, so we won’t explore it further. DSA 2013 Stacks n Queues

40 Priority Queues A priority queue is a more specialized data structure than a stack or a queue. Like an ordinary queue, a priority queue has a front and a rear, and items are removed from the front. However, in a priority queue, items are ordered by key value so that the item with the lowest key (or the highest key) is always at the front. Items are inserted in the proper position to maintain the order. DSA 2013 Stacks n Queues

41 Priority Queue Implementation
A priority queue can be implemented by a sorted array or a special kind of tree called a heap (we’ll see this later). Performance: insert takes O(n) time since we have to find the place where to insert the item delete takes O(1) time, since the smallest key is at the beginning DSA 2013 Stacks n Queues

42 Priority Queue Applications
Like stacks and queues, priority queues are often used as programmer’s tools. We’ll see one used in finding something called a minimum spanning tree for a graph later Priority-based OS process scheduler Priority queues are used in various ways in certain computer systems. In a multitasking operating system, for example, programs may be placed in a priority queue so the highest-priority program is the next one to execute. DSA 2013 Stacks n Queues

43 Efficiency of Stacks & Queues
Items can be both pushed and popped from the stack in constant O(1) time. That is, the time is not dependent on how many items are in the stack and is therefore very quick. No comparisons or moves are necessary. As with a stack, items can be inserted and removed from a queue in O(1) time. DSA 2013 Stacks n Queues


Download ppt "Stacks and Queues DSA 2013 Stacks n Queues."

Similar presentations


Ads by Google