Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

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 be instantiated.
The unorganized person’s data structure
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
Data Structure (Part I) Stacks and Queues. Introduction to Stack An stack is a ordered list in which insertion and deletions are made at one end. –The.
1 Stack and Queue. 2 Stack In Out ABCCB Data structure with Last-In First-Out (LIFO) behavior.
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:
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks CS 3358 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
Chapter 13 Pointers and Linked Lists. Nodes and Linked Lists Linked list: A sequence of nodes in which each node is linked or connected to the node preceding.
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.
Introduction to Stacks What is a Stack Stack implementation using arrays. Application of Stack.
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 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack.
Main Index Contents 11 Main Index Contents Stacks Further Stack Examples Further Stack Examples Pushing/Popping a Stack Pushing/Popping a Stack Class StackClass.
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.
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
Ceng-112 Data Structures ITurgut Kalfaoglu 1 Chapter 3 Stacks.
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
Data Structures: CSCI 362 – Stack Implementation Data Structures: CSCI 362 – Stack Implementation lecture notes adapted from Data Structures with C++ using.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
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.
Pointers OVERVIEW.
Introduction to Stacks Chapter 2. Objectives Introduce abstract data types. Discuss implementation types. – Static – Dynamic – Contiguous Introduce the.
FIST, Multi Media University Lecture 5 Stack (Array Implementation) Queue (Array Implementation )
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 19: Stacks and Queues.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 CS 132 Spring 2008 Chapter 7 Stacks Read p Problems 1-7.
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 19: Stacks and Queues (part 2)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
EC-211 DATA STRUCTURES LECTURE 9. Queue Data Structure An ordered group of homogeneous items or elements. Queues have two ends: – Elements are added at.
Data Structures & Algorithms
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
CHP-3 STACKS.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
11/07/141 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.
Stacks This presentation shows – how to implement the stack – how it can be used in real applications.
Main Index Contents 11 Main Index Contents Stacks Further Stack Examples Further Stack Examples Pushing/Popping a Stack Pushing/Popping a Stack Class StackClass.
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.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
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.
STACKS & QUEUES for CLASS XII ( C++).
Chapter 4 Stacks
Data Structures Using C++ 2E
Stacks Chapter 7 introduces the stack data type.
Stacks.
Stack and Queue APURBO DATTA.
Stacks Stack: restricted variant of list
Stacks Chapter 4.
Pointers and Linked Lists
Popping Items Off a Stack Lesson xx
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks and Queues Prof. Michael Tsai 2017/02/21.
Stacks Data structure Elements added, removed from one end only
Pointers & Dynamic Data Structures
Jordi Cortadella and Jordi Petit Department of Computer Science
Presentation transcript:

Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Stacks A list of items and a pointer to the "top" item in the list. Items can be inserted or removed from the list only at the top the list is ordered in the sequence of entry of items. Insertions and removals proceed in the "LIFO" last- in-first-out order. Functions:  Push: for putting objects into the stack  Pop: for taking objects out of the stack

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Stack Class Declaration # include typedef char DataType; const int MaxStackSize=50; class Stack { private: DataType stacklist[MaxStackSize]; int top; public: Stack(void); // constructor to initialize top //modification operations void Push(const DataType& item); DataType Pop(void); void ClearStack(void); //just copy top item without modifying stack contents DataType Peek(void) const; //check stack state int StackEmpty(void) const; int StackFull(void) const; };

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Stack Class Implementation Stack::Stack(void):top(-1) {} //Push void Stack::Push(const DataType& item)//same as //Push(DataType item) { //can not push if stack has exceeded its limits if (top==MaxStackSize-1) { cerr<<"Stack overflow"<<endl; exit(1); } // increment top ptr and copy item into list top++; stacklist[top] =item; } //pop DataType Stack::Pop(void) { DataType temp; // is stack empty nothing to pop if (top==-1) { cerr<<"Stack empty"<<endl; exit(1); } //record the top element temp=stacklist[ top] ; //decrement top and return the earlier top element top--; return temp; } //Peek is the same as Pop, except top is not moved DataType Stack::Peek(void) const {// write Peek as exercise } //Stack Empty int Stack::StackEmpty(void) const { return top==-1; //value is 1 if equal, 0 otherwise } // Stack Full int Stack::StackFull(void)const { return top==MaxStackSize-1; } //Clear Stack void Stack::ClearStack(void) { top=-1; }

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Stack Example Example: Write a program that uses a stack to test a given character string and decides if the string is a palindrome (i.e. reads the same backwards and forwards, e.g. "kabak", " a man a plan a canal panama", etc.) Algorithm:  first get rid of all blanks in the string  push the whole string character-wise, into a stack  pop out characters one by one, comparing with the characters of the original de-blanked string

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Stack Example Assuming that the stack declaration and implementation are in "astack.h“ # include “astack.h" # include void Deblank(char *s, char *t) { while (*s!=NULL) { if (*s!=' ') { *t=*s; t++; } s++; } *t=NULL; //append NULL to newstring } void main() { // create stack object to store string in reverse order. Stack S; char palstring[ 80], deblankedstring[ 80], c; int i=0; // string pointer bool ispalindrome=true; //we'll stop if false // get input cin.getline(palstring,80,'\n'); //remove blanks Deblank(palstring,deblankedstring);// A[],the array;A pointer to A[] //push character onto stack i=0; while(deblankedstring[ i] !=NULL) { S.Push(deblankedstring[ i] ); i++; } //now pop one-by-one comparing with original i=0; while (!S.StackEmpty()) { c=S.Pop(); //get out of loop when first nonmatch if (c!=deblankedstring[i]) { ispalindrome=false; break; } // continue till end of string i++; } //operation finished. Printout result if (ispalindrome) cout<<"\\"<<palstring<<"\\"<<"is a palindrome"<<endl; else cout<<"\\"<<palstring<<"\\"<<"is not a palindrome"<<endl; }

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Templates We use typedef to define the data type for the stack items for the stack class Stack class can be used only with that type of data in the program We want to use the same class or function definition for different types of items  Create different objects within the same class but with different data types  Define a general function that works on different data types  Link the data type with the object or function call and not with the whole program  A single function or class definition gives rise to a family of functions or classes that are compiled from the same source code, but operate on different types.  Stack A; Stack B; C++ allows this through Templates

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Templates template indicates that T 1,T 2,..T n are classes that will be used with a specific class upon creation of an object Note here that any operation in the template class or function must be defined for any possible data types in the template template int SeqSearch(T list  , int n, T key) /* T is a type that will be specified when SeqSearch is called */ { for (int i=0; i<n; i++) if (list  i  ==key) return i; return -1; } void main() { int A[10], Aindex float M[10], fkey=4.5, Mindex; Aindex=SeqSearch(A,10,25); /*search for int 25 in A */ Mindex=SeqSearch(M,100,fkey); /* search for float 4.5 in M */ }

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT A general stack const int MaxStackSize=50; template class Stack { private: T stacklist[MaxStackSize]; int top; public: Stack(void); // constructor to initialize top //modification operations void Push(const T& item); T Pop(void); void ClearStack(void); //just copy top item without modifying stack contents T Peek(void) const; //check stack state int StackEmpty(void) const; int StackFull(void) const; }; template Stack ::Stack(void):top(-1) {} template //Push void Stack ::Push(const T& item)//same as //Push(int item) { //can not push if stack has exceeded its limits if (top==MaxStackSize-1) { cerr<<"Stack overflow"<<endl; exit(1); } // increment top ptr and copy item into list top++; stacklist[top] =item; } template //pop T Stack ::Pop(void) { T temp; // is stack empty nothing to pop if (top==-1) { cerr<<"Stack empty"<<endl; exit(1); } //record the top element temp=stacklist[ top] ; //decrement top and return the earlier top element top--; return temp; }

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Example: Arithmetic expression evaluation Arithmetic expressions:  3+2*5=13 Correct  3+2*5=25 Incorrect Parentheses: ((11+1)/2-4 )*3=6 Operator precedence: Low to High: “(“ → -1 “)” → 0 +,- → 1 *, / → 2 exp→ 3 A “(“ starts a new expression which must be calculated before others currently being calculated→ 4 Rule for checking operator-operand matching: rank (state variable) 1. Initialize rank to 0 2. For each operand: add 1 3. For each binary operator: subtract 1 4. For unary operators and parentheses no action For each term the rank should be 0 or 1 For the full expression it must be 1

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Example: Arithmetic expression evaluation Two stacks:  Operator stack  Operand stack Algorithm:  Input operand: push it on operand stack  Input operator: Pop all operators which have stack precedence higher than or equal to the precedence of current operators  As operators are popped execute the operation on top stack operands, push result back.  e.g. input is “)“: Pop and evaluate all operators that are in the stack and have stack precedence greater than or equal to the input precedence of “)”  (Note that as stack precedence of “(“ is - 1, this loop stops when “(” is found and popped.) At end of expression: flush the operator stack evaluating operations. The rank must be 1. If rank <1 →operand missing. While clearing stack if “(“ found → ”)” missing. Final result: left on stack top CHECK Preiss book stack applications for a different example

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Example e.g. (3+5)/2e3 ((X oprinopn (33 +(+( +3 +(+( )8 Operator input -1 Operand input Operator input 1 Operand input Operator input 0 Pop + (higher precedence) Evaluate + Pop ( Push 8 on stack //8 oprinopn / e/e/ e 2828 e/e/ / 8888 Operator input 2 Operand input Operator input 3 Operand input Pop / Evaluate / Push 1 on stack 1 Operator input 0 Evaluate + Pop ( e/e/ Pop e Evaluate e Push 8 on stack Finished Flush stack

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Queues A queue is a data structure that stores elements in a list and permits data access only at the two ends of the list. An element is inserted only at the “rear” end of the list and deleted from only the “front” end of the list. Elements are removed in the same order in which they are stored and hence a queue provides FIFO(first-in/first-out) or FCFC(first- come/first-served) ordering

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Queues f,r c=0 2. insert `A’: f c=1r 3. insert `B’: fc=2 r AB 4. insert `C’: f c=3r A ABC 1. initially: count=0, front=0, rear=0 5. delete: f c=2r ABC not accessible any more 6. insert `D’: f c=3 r BCD NOTE: CIRCULAR OPERATION i.e., move rear & front forward: rear=(rear+1)%MaxQSize front=(front+1)%MaxQSize etc.

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT A General Queue # include const int MaxQSize=50; template class Queue { private: // queue array and its parameters int front, rear, count; T qlist[ MaxQSize] ; public: //constructor Queue(void); // initialize data members //queue modification operations void Qinsert(const T& item); T QDelete(void); void ClearQueue(void); // queue access T QFront(void) const; // queue test methods int QLength(void) const; int QEmpty(void) const; int QFull(void) const; }; // Queue constructor //initialize queue front, rear, count template Queue ::Queue(void): front(0), rear (0), count(0) {} //Queue Operations // Qinsert: insert item into the queue template void Queue ::Qinsert(const T& item) { // terminate if queue is full if (count==MaxQSize) { cerr<<"Queue overflow!" <<endl; exit(1) } //increment count, assign item to qlist and update rear count++; qlist[ rear] =item; rear=(rear+1)% MaxQSize; } //QDelete : delete element from the front of the queue and return its value template T Queue ::QDelete(void) { T temp; // if qlist is empty, terminate the program if (count==0) { cerr<<"Deleting from an empty queue!"<<endl; } //record value at the front of the queue temp=qlist[ front] ; //decrement count, advance front and return former front count --; front=(front+1) % MaxQsize; return temp; }

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT References Data Structures with C++, William H. Ford,William R. Topp es/EE441/ch1/classes.html es/EE441/ch1/classes.html