E.G.M. Petrakislists, stacks, queues1 Stacks Stack: restricted variant of list –Elements may by inserted or deleted from only one end  LIFO lists –Top:

Slides:



Advertisements
Similar presentations
Data Structures Through C
Advertisements

Stacks, Queues, and Linked Lists
§3 The Stack ADT 1. ADT A stack is a Last-In-First-Out (LIFO) list, that is, an ordered list in which insertions and deletions are.
Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
CS Data Structures ( 資料結構 ) Chapter 3: Stacks and Queues Spring 2012.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
CS 206 Introduction to Computer Science II 03 / 04 / 2009 Instructor: Michael Eckmann.
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
 Balancing Symbols 3. Applications
Queue RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Stack and Queue COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
E.G.M. Petrakisstacks, queues1 Stacks  Stack: restricted variant of list  elements may by inserted or deleted from only one end : LIFO lists  top: the.
Stacks and Queues COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
CS 206 Introduction to Computer Science II 03 / 06 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 10 / 17 / 2008 Instructor: Michael Eckmann.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Queues.
Stacks, Queues & Deques CSC212.
CS 206 Introduction to Computer Science II 10 / 15 / 2008 Instructor: Michael Eckmann.
Stacks CS-240 & CS-341 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed.
E.G.M. Petrakislists, stacks, queues1 Lists List: finite sequence of data elements –Ordered: each element has a position in list –All elements has the.
CS 206 Introduction to Computer Science II 10 / 28 / 2009 Instructor: Michael Eckmann.
Chapter 16 Stacks and Queues Saurav Karmakar Spring 2007.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
Stack  A stack is a linear data structure or abstract data type for collection of items, with the restriction that items can be added one at a time and.
Objectives of these slides:
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Data Structures: CSCI 362 – Stack Implementation Data Structures: CSCI 362 – Stack Implementation lecture notes adapted from Data Structures with C++ using.
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
Review of Lists, Stacks, and Queues CS 400/600 – Data Structures.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Stacks Stack is a data structure that can be used to store data which can later be retrieved in the reverse or last in first out (LIFO) order. Stack is.
1 Stacks & Queues CSC Stacks & Queues Stack: Last In First Out (LIFO). –Used in procedure calls, to compute arithmetic expressions etc. Queue: First.
CHP-3 STACKS.
Stacks & Queues. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy to use.
Prof. I. J. Chung Data Structure #5 Professor I. J. Chung.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
 In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station.
CSC 172 DATA STRUCTURES. A TALE OF TWO STRUCTURES.
STACKS & QUEUES for CLASS XII ( C++).
Queues.
Stacks Stacks.
Infix to postfix conversion
Homework 4 questions???.
Objectives In this lesson, you will learn to: Define stacks
CSC 172 DATA STRUCTURES.
Stacks Stack: restricted variant of list
Data Structures – Week #3
Stack application: postponing data usage
Visit for more Learning Resources
Stack.
CMSC 341 Lecture 5 Stacks, Queues
Mark Allen Weiss, Addison Wesley
Stacks and Queues 1.
Stack.
Data Structures – Week #3
Stacks A stack is an ordered set of elements, for which only the last element placed into the stack is accessible. The stack data type is also known as.
Presentation transcript:

E.G.M. Petrakislists, stacks, queues1 Stacks Stack: restricted variant of list –Elements may by inserted or deleted from only one end  LIFO lists –Top: the accessible end of the list –Operations: “push”, “pop” –Many applications –Easy to implement Arrays Linked lists FEDCBAFEDCBA top

E.G.M. Petrakislists, stacks, queues2 Checking mathematical expressions –Equal number of left/right (, {, [, ), }, ] wrong

E.G.M. Petrakislists, stacks, queues3 Algorithm: read the expression from left to right –p: next symbol in expression –Repeat until (empty(stack) ) { read(p); If p = ( or { or [ then push(stack,p); loop; if p = ) or } or ] then c = pop(stack); if c != p then error!! } if (not empty(stack) ) then error!!

E.G.M. Petrakislists, stacks, queues4 [((([((( (

E.G.M. Petrakislists, stacks, queues5 Array-based implementation: a simplified version of list implementation –Array of fixed size –Top: always the first element (0-th element) –Current is always the top element –push  insert at current! –pop  remove current!

E.G.M. Petrakislists, stacks, queues6 class Stack { private: int size;// Max size int top;// Top ELEM ELEM * listarray; //Array holding ELEM's public: Stack (const int sz = LIST_SIZE)//Constructor:initialize {size = sz; top = 0; listarray = new ELEM[sz};} ~Stack( ) { delete [ ] listarray;} //Destructor: return array space void clear( ) {top = 0;} //Remove all ELEM's void push(const ELEM& item) //Push ELEM onto stack {assert (top<size); listarray[top++] = item;} ELEM pop( )// Pop ELEM from top of stack {assert (!isEmpty( )); return listarray[--top];} ELEM topValue( ) const//Return value of top ELEM {assert(!isEmpty( )); return listarray[top-1];} bool isEmpty( ) const //Return TRUE if stack is empty {return top==0;} }; size top size

E.G.M. Petrakislists, stacks, queues7 Linked list implementation: simplified version of the linked list implementation –The head and tail pointers of the list implementation are not used top

E.G.M. Petrakislists, stacks, queues8 class Stack { private: link *top;//Pointer to top stack ELEM public: Stack (const int) //Constructor: initialize { top = NULL;} ~Stack( ) { clear( );} //Destructor: return ELEMs void clear( ) { } //Remove all ELEM's void push(const ELEM& item)//Push ELEM onto stack {top = new link(item, top);} ELEM pop( ); ELEM topValue( ) const //Return value of top ELEM {assert(!isEmpty( )); return top  element;} bool isEmpty( ) const //Return TRUE if empty {return top == NULL;} };

E.G.M. Petrakislists, stacks, queues9 More applications of stacks: evaluation of arithmetic expressions –Conversion of infix to postfix or prefix –Evaluation of the postfix or prefix –Infix, prefix, postfix: refer to the relative position of the operator with respect to the operands –infix : A+B –prefix : +ABpolish –postfix : AB+reverse polise

E.G.M. Petrakislists, stacks, queues10 Convert infix to prefix or postfix –Read from left to right –First convert operations of higher precedence Parenthesis have the highest precedence “^” have precedence over “*”, “/” have the same precedence but higher than “+”, “-” which all have the same precedence –The converted prefix or postfix part is treated as a single operand –If all operators have the same precedence then convert from left to right

E.G.M. Petrakislists, stacks, queues11 Infix to postfix A+B * C : ‘ * ’ > ‘+’ - A+(B * C) : equivalent - Α+(ΒC * ) : B*C to postfix - ABC * + : postfix (A+B) * C : (…) > ‘ * ’ - (AB+) * C : A+B to postfix - (AB+)C * : (AB+) * C to postfix - AB+C * : postfix Postfix and Prefix have no parenthesis !!

E.G.M. Petrakislists, stacks, queues12 Infix to postfix A+B-C : ΑΒ+C- - (A+B) * (C-D) : AB+CD- * - Α$Β * C-D+E/F/(G+H) : AB$C * D-EF/GH+/+ - A-B/(C * D$E) : ABCDE$ * /- Infix to prefix A+B-C : -+ABC - (A+B) * (C-D) : * +AB-CD - A$B * C-D+E/F/(G+H) : +- * $ABCD//EF+GH - A-B/(C * D$E) : -A/B * C$DE

E.G.M. Petrakislists, stacks, queues13 Evaluation of postfix expressions: While (not end of expression) { read symbols from left to right; result = 0 if (symbol == operand) push (stack); else { operator1 = pop(stack); operator2 = pop(stack); result = operator1 operand operator2; push(stack, result); } result = pop(stack);

E.G.M. Petrakislists, stacks, queues14 Postfix: / + * 2 $ 3 + Symbol / + * 2 $ 3 + Operand Operand Value stack Operand 6 6,2 6,2,3 6,5 1 1,3 1,3,8 1,3,8,2 1,3,4 1,7 7 7, ,3 52

E.G.M. Petrakislists, stacks, queues15 Convert infix to postfix: read expression from left to right –Output operands –Push operators to stack –Higher precedence operators must be above lower precedence operators –Before pushing an operator into the stack check the precedence of operators already in the stack if operator in stack has higher precedence  output this operator and then insert the current operator in the stack “(”, “[”, “{” have higher precedence, push in stack if “)”, “]”, “}” pop stack until “(”, “[”, “{” is found don’t output “(”, “[”, “{”, “)”, “]”, “}”

E.G.M. Petrakislists, stacks, queues16 Example: (A + B) * C –push “ ( ” in stack –output A –push “+” in stack –output B –don’t push “ ) ”, pop all operators in stack –output “+”, ignore “ ( ”, “ ) ” –“ * ” push in stack –output C –output “+”

E.G.M. Petrakislists, stacks, queues17 Symbol ( A + B ) * C Postfix A AB AB+ AB+C AB+C * Stack ( (+ * Example: (A + B) * C

E.G.M. Petrakislists, stacks, queues18 stack = NULL; while (not end of input) { symbol = read next symbol; if (symbol == operand) output(symbol); else { while (not empty(stack)) and precedence(stack(top) > precedence(symbol)) { top symbol = pop(stack); output(top symbol); } push(stack, symbol); } while not_empty(stack) { top symbol = pop(stack); output(top symbol); }

E.G.M. Petrakislists, stacks, queues19 Queue Queue elements may only be inserted from the rear and removed from the front –Restricted form of list –FIFO: first in first out –Insert: enqueue operation –Remove: dequeue operator

E.G.M. Petrakislists, stacks, queues20 A B C A B C D B C D front rear enqueue (queue, D) dequeue (queue)

E.G.M. Petrakislists, stacks, queues21 Array-based implementation: –If the elements are the first n elements of array –And the rear element is at position 0 –dequeue requires Θ(1) operations but, –enqueue requires Θ(n) operations (all elements must be shifted) –The reverse if the last element is at n-1 position –The condition of empty queue is also a problem

E.G.M. Petrakislists, stacks, queues22 front = 4 rear = 4 front = 4 rear = A Condition of empty queue: rear = front Initial values: rear = front = LIST_SIZE - 1 front points to the position proceeding the first element

E.G.M. Petrakislists, stacks, queues23 D C B Α E D C B Α front = 4 rear = 2 front = 4 rear = 3 front = 4 rear = 4 The condition of empty queue is true but the queue is not empty  “E” cannot be inserted: The last array position must be left empty C B Α

E.G.M. Petrakislists, stacks, queues24 D C B Delete “Α” front = 0 rear = 3 D C Delete “B” front = 1 rear = 3

E.G.M. Petrakislists, stacks, queues25 E D C F Insert “E”, “F” Circular list front = 1 rear = 0

E.G.M. Petrakislists, stacks, queues26 class Queue { private: int size; // size of queue int front; // Index prior to front item int rear; // Index of rear item Elem *listarray; // Array holding the list Elem's public: Queue(int sz = LIST_SIZE) // array one position larger for empty slot { size = sz + 1; front = rear = 0; listarray = new Elem[size]; } ~Queue( ) { delete [ ] listarray; } void clear( ) { front = rear; } // Clear queue void enqueue(const Elem); // Enqueue Elem at rear Elem dequeue( ); // Dequeue Elem from front Elem firstValue( ) const // Get value of front Elem { assert(!isEmpty( )); return listarray[(front+1) % size]; } bool isEmpty( ) const // TRUE if queue is empty { return front == rear; } }; size front rear size

E.G.M. Petrakislists, stacks, queues27 // Enqueue Elem at rear of queue void Queue::enqueue(const Elem item) { assert(((rear+1) % size) != front); // Queue must not be full rear = (rear+1) % size; // Increment rear (in circle) listarray[rear] = item; } // Dequeue Elem from front of queue Elem Queue::dequeue( ) { assert(!isEmpty()); // There must be something to dequeue front = (front+1) % size; // Increment front return listarray[front]; // Return value }

E.G.M. Petrakislists, stacks, queues28 Linked-list implementation: simple adaptation of the linked list implementation –Current always points to the first element –The head pointer of the list implementation is not used front rear

E.G.M. Petrakislists, stacks, queues29 class Queue{//Linked queue class private: link* front; // Pointer to front queue node link* read; // Pointer to rear queue node public: Queue( ) // Constructor: initialize { front = rear = NULL;} ~Queue( ) { clear( );} // Destructor: return link ELEMs void clear( ); //Remove all ELEM's from queue void enqueue(const ELEM &);//Enqueue ELEM at rear ELEM dequeue( );//Dequeu ELEM from front ELEM firstValue( ) const//Get value of front ELEM { assert(!isEmpty( )); return front  element;} bool isEmpty( ) const//Return TRUE if queue is empty { return front == NULL; };

E.G.M. Petrakislists, stacks, queues30 void Queue::clear() { //Remove all ELEM's from the queue while (front != NULL) //Return link nodes to freelist {rear = front; front = front  next; delete rear;} rear = NULL; } //Enqueue ELEM at rear of queue void Queue::enqueue (const ELEM& item){ if (rear != NULL){ //Queue not empty: add to end rear  next = new link(item,NULL); rear=rear  next; }else front = rear = new link(item, NULL); //Empty queue } ELEM Queue::dequeue( ) { //Dequeue ELEM from front assert(!isEmpty( )); //Must be something to Dequeue ELEM temp=front  element; //Store dequeued value link* ltemp = front;//Hold onto dequeued link node front=front  next;// Advance front delete ltemp;//Return link to free store if (front == NULL) rear = NULL; //Dequeued last element; return temp;//Return element value }

E.G.M. Petrakislists, stacks, queues31 Priority Queue Ascending: elements in any order but dequeue removes the minimum Descending: dequeue removes the maximum

E.G.M. Petrakislists, stacks, queues32 Ε D G Α front = 5 rear = 4 Ε D G front = 5 rear = 4 front = 5 rear = 4 ascendingdescending Ε D Α ?

E.G.M. Petrakislists, stacks, queues33 Problem: in the array implementation, dequeue creates empty slots Solution(1): move elements  Θ(n) operations on dequeue Solution(2): store elements in ascending (descending) order  Θ(n) operations on enqueue Ε D G Α E D Α Ε D G Α E D Α