Chapter 3 Stack and Queue 3.3 The Stack ADT 3.3.1. Stack Model A stack is a list in which insertions and deletions take place at the same end. This end.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Chapter 3: Lists, Stacks and Queues Concept of Abstract Data Type (ADTS) How to efficiently perform operations on list Stack ADT and its applications Queue.
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
§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.
CSCE 3110 Data Structures & Algorithm Analysis Stacks and Queues Reading: Chap.3 Weiss.
ADVANCED DATA STRUCTURES AND ALGORITHM ANALYSIS Chapter 3 Lists, Stacks, and Queues.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Queues CS 308 – Data Structures. What is a queue? It is an ordered group of homogeneous items of elements. Queues have two ends: –Elements are added at.
Queues CS 3358 – Data Structures. What is a queue? It is an ordered group of homogeneous items of elements. Queues have two ends: – Elements are added.
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
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.”
LINKED QUEUES P LINKED QUEUE OBJECT Introduction Introduction again, the problem with the previous example of queues is that we are working.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Data Structure Dr. Mohamed Khafagy.
Queue Overview Queue ADT Basic operations of queue
Chapter 3 1. Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can.
 Balancing Symbols 3. Applications
Doubly-Linked Lists Same basic functions operate on list Each node has a forward and backward link: What advantages does a doubly-linked list offer? 88.
Stack and Queue COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
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.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Lecture 8 Feb 19 Goals: l applications of stack l Postfix expression evaluation l Convert infix to postfix l possibly start discussing queue.
1 Lecture 24 Abstract Data Types (ADT) –I Overview  What is an Abstract Data type?  What is Stack ADT?  Stack ADT Specifications  Array Implementation.
1 Stack Data : a collection of homogeneous elements arranged in a sequence. Only the first element may be accessed Main Operations: Push : insert an element.
Chapter 16 Stacks and Queues Saurav Karmakar Spring 2007.
Stacks CSE, POSTECH. 2 2 Stacks Linear list One end is called top. Other end is called bottom. Additions to and removals from the top end only.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
1 Stacks – Chapter 3 A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. Alternatively,
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Stack and Queue.
L.Chen1 Chapter 3 DATA REPRESENTATION(2) L.Chen A Chain Iterator Class A Chain Iterator Class ( 遍历器类 )  An iterator permits.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
Chapter 16 Stacks & Queues. Objective In this chapter we will learn:  Stacks  Queues  Different implementations (arrays and linked list) of both 
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Intro. to Data Structures Chapter 3: Lists, Stacks, Queues 1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types (ADTs) Lists Stacks Queues.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture6.
Lab 7 Queue ADT. OVERVIEW The queue is one example of a constrained linear data structure. The elements in a queue are ordered from least recently added.
Queues CS 302 – Data Structures Sections 5.3 and 5.4.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
Stacks And Queues Chapter 18.
CMSC 341 Deques, Stacks and Queues. 2/20/20062 The Double-Ended Queue ADT A Deque (rhymes with “check”) is a “Double Ended QUEue”. A Deque is a restricted.
Lecture 20 Stacks and Queues. Stacks, Queues and Priority Queues Stacks – first-in-last-out structure – used for function evaluation (run-time stack)
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
M180: Data Structures & Algorithms in Java Queues Arab Open University 1.
Stacks & Queues. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy to use.
1 Queues Chapter 4. 2 Objectives You will be able to Describe a queue as an ADT. Build a dynamic array based implementation of a queue ADT.
栈 栈的应用 栈的应用 队列 队列 优先队列 优先队列 a1a1 a2a2 a3a3 a4a4 a5a5 a6a6 插入 x i 删除 x j 插入 删除 栈 ( Stack )
1 Data Structures CSCI 132, Spring 2014 Lecture 7 Queues.
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
Session 03 - Templates Outline 03.1Introduction 03.2Function Templates 03.3Overloading Template Functions 03.4Class Templates 03.5Class Templates and Non-type.
1 Data Structures and Algorithms Queue. 2 The Queue ADT Introduction to the Queue data structure Designing a Queue class using dynamic arrays Linked Queues.
CS505 Data Structures and Algorithms
Stack and Queue APURBO DATTA.
CMSC 341 Lecture 5 Stacks, Queues
Deques, Stacks and Queues
Stack and Queues Stack implementation using Array
CSC 143 Stacks [Chapter 6].
Stacks and Queues 1.
Stacks and Queues CSE 373 Data Structures.
CMSC 341 Stacks and Queues 4/17/2019.
CMSC 341 Stacks and Queues 4/17/2019.
Stacks.
CMSC 341 Stacks and Queues 4/29/2019.
Queues.
CMSC 341 Lecture 7.
Presentation transcript:

Chapter 3 Stack and Queue

3.3 The Stack ADT Stack Model A stack is a list in which insertions and deletions take place at the same end. This end is called the top. The other end of the list is called the bottom. It is also called a LIFO(last-in-first-out) list.

Stack Model E  top D  top D C C B B B  top A  bottom A  bottom A  bottom

Stack Model AbstractDataType Stack{ instances list of elements; one end is called the bottom; the other is the top; operations Create():Create an empty stack; IsEmpty():Return true if stack is empty,return false otherwise IsFull ():Return true if stack if full,return false otherwise; Top():return top element of the stack; Add(x): add element x to the stack; Delete(x):Delete top element from stack and put it in x; }

Implementation of Stack 1. Linked List Implementation of Stacks ^ topOfStack element next …… when topOfStack= = null is empty stack

Linked List Implementation of Stacks public class StackLi (3.37) { public StackLi( ){ topOfStack = null; } public boolean isFull( ){ return false; } public boolean isEmpty( ){ return topOfStack = = null; } public void makeEmpty( ){ topOfStack = null; } public void push( object x ){ /* Figure 3.38 */ } public object top( ){ /*Figure 3.39 */ } public void pop( ) throws Underflow{ /* Figure 3.40 */ } public object topAnPop( ){ /* Figure 3.41 */ } private ListNode topOfStack; } Class skeleton for linked list implementation of the stack ADT

Linked List Implementation of Stacks Some Routine: public void push( object x ) (3.38) { topOfStack = new ListNode( x, topOfStack ); } public object top( ) (3.39) { if( isEmpty( ) ) return null; return topOfStack.element; }

Linked List Implementation of Stacks public void pop( ) throws Underflow { if( isEmpty( ) ) (3.40) throw new Underflow( ); topOfStack = topOfStack.next; } public object topAndPop( ) (3.41) { if( isEmpty( ) ) return null; object topItem = topOfstack.element; topOfStack = topOfStack.next; return topItem; }

Implementation of Stack 2. Array Implementation of Stacks theArray topOfStack e 1 e 2 e 3 e n when topOfStack= = -1 is empty stack

Array Implementation of Stacks public class stackAr { public StackAr( ){ /*Figure 3.43 */ } public StackAr( int capacity ){ /*Figure 3.43 */ } public boolean isEmpty( ){ return topOfStack = = -1; } public boolean isFull( ){ return topOfStack = = theArray.length – 1; } public void makeEmpty( ){ topOfStack = -1; } public void push( object x ) throws overflow{ /*Figure 3.44 */ } public object top( ){ /*Figure 3.45 */ } public void pop( ) throws Underflow{ /*Figure 3.46 */ } public object topAndPop( ){ /*Figure 3.47 */ } private object [ ] theArray; private int topOfStack; static final int DEFAULT_CAPACITY = 10; } Stack class skeleton---array implementation

Array Implementation of Stacks Some routine: public StackAr( ) ( 3.43) { this( DEFAULT_CAPACITY ); } public StackAr( int capacity ) { theArray = new object [capacity ]; topOfStack = -1; } Stack construction---array implementation

Array Implementation of Stacks public void push( object x ) throws Overflow (3.44) { if ( isfull( ) ) throw new Overflow( ); theArray[ ++topOfStack ] = x; } public object top( ) { if( isEmpty( ) return null; return theArray[ topOfStack ]; }

Array Implementation of Stacks public void pop( ) throws Underflow { if( isEmpty( ) ) throw new Underflow( ); theArray[ topOfStack-- ] = null; } public object topAndPop( ) { if( isEmpty( ) ) return null; object topItem = top( ); theArray[ topOfStack-- ] = null; reurn topItem; }

Array Implementation of Stacks It is wasteful of space when multiple stacks are to coexist When there’s only two stacks, we can maintain space and time efficiency by pegging the bottom of one stack at position 0 and the bottom of the other at position MaxSize-1. The two stacks grow towards the middle of the array.

Array Implementation of Stacks 0 MaxSize- 1 top1 top2 Stack1Stack2 ……… Two stacks in a array

3.3.3.Applications 1. Balancing Symbols(Parenthesis Matching) 2. Expression Evaluation

1.Parenthesis Matching (a*(b+c)+d) (a+b))(

#include #include “stack.h” const int Maxlength = 100; // max expression length void PrintMatchedPairs(char *expr) { Stack s(Maxlength); int j, length = strlen(expr); for ( int i = l; i <= length; i++) { if ( expr[i-1]= =‘(‘) s.Add(i); else if (expr[i-1]= =‘)’) try {s.Delete(j); cout <<j<<‘ ‘ <<i<< endl;} catch (OutOfBounds) {cout << “No match for right parenthesis” << “ at “<< i << endl;} } while ( !s.IsEmpty ()) { s.Delete(j); cout<< “No match for left parenthesis at “ << j << endl;} }

void static main(void) { char expr[MaxLength]; cout<< “type an expression of length at most” <<MaxLength<<endl; cin.getline(expr, MaxLength); cout<<“the pairs of matching parentheses in “ <<endl; puts(expr); cout<<“are”<<endl; printMatcnedPairs(expr); }

2.Expression Evaluation compiler: infix Expression postfix Expression postfix Expression Evaluation A*B-C*D# AB*CD*-# (A+B)*((C-D)*E+F)# AB+CD-E*F+*# postfix Expression Evaluation AB*CD*-# infix Expression postfix Expression A*B-C*D# AB*CD*-#

postfix Expression Evaluation enum Boolean {False, True}; #include class calculator { public: calculator(int sz) :s (sz) { } void Run( ); void clear( ); private: void AddOperand (double value) ; Boolean Get2Operands(double & left, double & right) ; void DoOperator (char op) ; stack s ; };

void calculator:: AddOperand(double value) { s.Push(value); } Boolean calculator::Get2Operands(double &left, double &right) { if (s.IsEmpty()) {cerr<<“Missing Operand!”<<endl; return false;} right = s.Pop(); if (s.IsEmpty()) {cerr<<“Missing Operand!”<<endl; return false;} left = s.Pop(); return true; }

void calculator :: DoOperator(char op) { double left, right; Boolean result; result = Get2Operands(left, right); if (result= =true) Switch (op) { case ‘+’: s.Push (left + right) ; break; case ‘-’ : s.Push (left - right) ; break; case ‘*’ : s.Push (left * right) ; break; case ‘/’ : if (right = = 0.0) {cerr << “divide by 0!” << endl; s.Clear ( ); } eles s.Push(left / right) ; break; case ‘^’ : s.Push (power (left, right) ); break; } else s.Clear ( ); }

void Calculator:: Run () { char ch; double newoperand; while ( cin >>ch, ch != ‘#‘) { switch (ch) { case ‘+’: case ‘-’: case ‘*’: case ‘/’: case ‘^’: DoOperator (ch); break; default: cin. Putback(ch); cin >> newoperand; AddOperand(newoperand); break; } } }

void Calculator::clear() { s.MakeEmpty(); } #include void main () { Calculator CALC(10); CALC.Run(); }

infix Expression postfix Expression void postfix (expression e) { Stack s ; char ch, y; s.MakeEmpty ( ) ; s.Push (‘#’); while (cin.get ( ch ), ch != ‘#’) { if (isdigit ( ch )) cout << ch; else if (ch = = ‘)’) for (y=s.Pop( ); y!= ‘(‘; y=s.Pop( )) cout << y ; else { for (y = s.Pop ( ); isp (y) > icp (ch); y=s.Pop(y)) cout<<y ; s.Push (y) ; s.Push (ch); } } while (! s.IsEmpty ( )) { y = s.Pop ( ) ; cout <<y ; } }

Chapter 3----stack exercises: 1. P a Chinese: P a 实习题: 2. 中缀表达式 后缀表达式 对后缀表达式求值, 合为一趟来做。

3.4. The Queue ADT A queue is a linear list in which additions and deletions take place at different ends. It is also called a first-in-first-out list. The end at which new elements are added is called the rear. The end from which old elements are deleted is called the front.

Queue Model Sample queues front rear front rear front rear A B C B C B C D Delete A Add D

Queue Model AbstractDataType Queue { instances ordered list of elements;one end is called the front; the other is the rear; operations Create(): Create an empty queue; IsEmpty(): Return true if queue is empty,return false otherwise; IsFull(): return true if queue is full, return false otherwise; First(): return first element of the queue; Last(): return last element of the queue; Add(x): add element x to the queue; Delete(x): delete front element from the queue and put it in x; }

Array Implementation of Queue A B C …… theArray: front back n-1 X currentSize the queue size : currentSize; an empty queue has currentSize= = 0; an full queue has currentSize= = theArray.length;

Array Implementation of Queue To add an element: back=back+1; theArray[back]=x; To delete an element: two methods: 1) front=front+1; O(1) 2) shift the queue one position left. O(n)

Array Implementation of Queue front back front back front back A B C … B C … B C D …

Array Implementation of Queue … A B C D E Front back Free space

Array Implementation of Queue to use a circular array to represent a queue back C B A front back C B A front D Addtion

Array Implementation of Queue deletion C B A front D back deletion C B front back D

Array Implementation of Queue How implementation a circular array: 1)When front or back reachs theArray.length-1, reset 0 1)back = (back+1) % theArray.length front = (front + 1) % theArray.length

Array Implementation of Queue Public class QueueAr { public QueueAr( ){ /* Figure 3.52 */ } public QueueAr( int capacity ){ /* Figure 3.52 */ } public boolean isEmpty( ){ return currentsize = = 0; } public boolean isfull( ){ return currentSize = = theArray.length; } public void makeEmpty( ){ /* Figure 3.52 */ } public Object getfront( ){ /* see online code */ } public void enqueue( Object x ) throw Overflow{/* Figure 3.53 */ } private int increment( int x ){/* Figure 3.53 */ } private Object dequeue( ){ /* Figure 3.54 */ } private Object [ ] theArray; private int currentSize; private int front; private int back; static final int DEFAULT_CAPACITY = 10; }

Array Implementation of Queue public QueueAr( ) { this( DEFAULT_CAPACITY ); } public QueueAr( int capacity ) { theArray = new Object[ CAPACITY ]; makeEmpty( ); } public void makeEmpty( ) { currentSize = 0; front = 0; back = -1; } Figure 3.52

Array Implementation of Queue public void enqueue( object x ) throw Overflow { if( isFull( ) ) throw new Overflow( ); back = increment( back ); theArray[ back ] = x; currentSize++; } private int increment( int x ) { if( ++x = = theArray.length ) x = 0; return x; } Figure 3.53

Array Implementation of Queue public Object dequeue( ) { if( isEmpty( ) ) return null; currentSize--; Object fromtItem = theArray[ front ]; theArray[ front ] = null; front = increment( front ); return frontItem; } Figure 3.54

3.4.3 Linked Representation of queue Linked queues data link …… ^ front back a1a1 a2a2 an an

3.4.3 Linked Representation of queue Class definition for a linked queue template class LinkedQueue { public: LinkedQueue(){front=back=0;} ~LinkedQueue(); bool IsEmpty()const{return ((front)?false:true);} bool IsFull()const; T First()const; T Last()const; LinkedQueue &Add(const T& x); LinkedQueue & Delete(T& x); privarte: Node *front; Node *back; };

3.4.3 Linked Representation of queue 1)destructor template LinkedQueue ::~LinkedQueue() { Node *next; while(front) { next=front.link; delete front; front=next; } }

3.4.3 Linked Representation of queue 2)Add(x) template LinkedQueue & LinkedQueue ::Add(const T&x) { Node *p=new Node ; p. data=x; p. link=0; if(front) back. link=p; else front=p; back=p; return *this; }

3.4.3 Linked Representation of queue 3)Delete(x) template LinkedQueue & LinkedQueue ::Delete(T& x) { if(IsEmpty())throw OutOfBounds(); x=front. data; Node * p=front; front=front. link; delete p; return *this; }

3.4.4 Application 1) Print the coefficients of the binomial expansion (a+b) i, i=1,2,3,…,n

Print the coefficients of the binomial expansion #include #include “queue.h” void YANGHUI(int n) { Queue q; q.makeEmpty( ); q.Enqueue(1); q.EnQueue(1); int s=0; for (int i=1; i<=n;i++) { cout << endl; for (int k=1;k<=10-i;k++) cout<<‘ ‘; q.EnQueue(0); for (int j=1;j<=i+2;j++) { int t=q.DeQueue( ); q.EnQueue(s+t); s=t; if (j!=i+2) cout<< s <<‘ ‘; } } }

2)Wire Routing a b A 7*7 grad A wire between a and b

2)Wire Routing a b b a Distance labeling Wire path

2)Wire Routing b ool FindPath(Position start, Position finish, int & PathLen, Position * & path) { if (( start.row = = finish.row) &&(start.col = = finish.col)) { PathLen = 0; return true;} for ( int i = 0; i<= m+1; i++) { grid[0][i] = grad[m+1][i] = 1; grid[i][0] = grad[i][m+1] = 1;} Position offset[4]; offset[0].row = 0; offset[0].col = 1; offset[1].row = 1; offset[1].col = 0; offset[2].row = 0; offset[2].col = -1; offset[3].row = -1; offset[3].col = 0; int NumOfNbrs = 4; Position here, nbr; here.row = start.row; here.col = start.col; grid[start.row][start.col] = 2;

2)Wire Routing LinkedQueue Q; do{ //label neighbors of here for ( int i = 0; i< NumOfNbrs; i++) { nbr.row = here.row + offset[i].row; nbr.col = here.col + offset[i].col; if (grid[nbr.row][nbr.col] = = 0) { grid[nbr.row][nbr.col] = grid[here.row][here.col]+1; if ((nbr.row = = finish.row) &&(nbr.col = = finish.col)) break; Q.Add(nbr); }// end of if }// end of for if (( nbr.row = = finish.row) && (nbr.col = = finish.col)) break; if (Q.IsEmpty()) return false; Q.Delete(here); } while(true);

2)Wire Routing PathLen = grid[finish.row][finish.col]-2; path = new Position [PathLen]; //trace backwards from finish here = finish; for ( int j = PathLen-1; j >= 0; j--) { path[j] = here; for ( int i = 0; i < NumOfNbrs; i++) { nbr.row = here.row + offset[i].row; nbr.col = here.col + offset[i].col; if ( grid[nbr.row][nbr.col] = = j+2) break; } here = nbr; } return true; }

queue exercises: 1. P P Chinese: 1. P P 补充: 3. 假设以数组 Q[m] 存放循环队列中的元素,同时以 rear 和 length 分别指示环形队列中的队尾位置和队列中所含元 素的个数: 1 )求队列中第一个元素的实际位置。 2 )给出该循环队列的队空条件和队满条件,并写出 相应的插入 (enqueue) 和删除 (dlqueue) 元素的操作算法。