Lists, Stacks and Queues

Slides:



Advertisements
Similar presentations
Data Structures Through C
Advertisements

Stack & Queues COP 3502.
§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)
Lec 7 Sept 17 Finish discussion of stack infix to postfix conversion Queue queue ADT implementation of insert, delete etc. an application of queue.
Data Structures and Algorithms (60-254)
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.
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:
CS 206 Introduction to Computer Science II 03 / 04 / 2009 Instructor: Michael Eckmann.
Queue Overview Queue ADT Basic operations of queue
 Balancing Symbols 3. Applications
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
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.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
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.
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.
Lists, Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Stacks, Queues & Deques CSC212.
Stacks and Queues.
Stack: Linked List Implementation Push and pop at the head of the list New nodes should be inserted at the front of the list, so that they become the top.
Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Lecture 11 Sept 26, 2011 Goals convert from infix to postfix.
Definition Stack is an ordered collection of data items in which access is possible only at one end (called the top of the stack). Stacks are known.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Objectives of these slides:
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
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)
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Computer Science Department Data Structures and Algorithms Queues Lecture 5.
1 Stacks & Queues CSC Stacks & Queues Stack: Last In First Out (LIFO). –Used in procedure calls, to compute arithmetic expressions etc. Queue: First.
Lists, Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Stacks & Queues. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy to use.
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.
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.
Data Structures Using C++ 2E
Review Array Array Elements Accessing array elements
Data Structure By Amee Trivedi.
CC 215 Data Structures Queue ADT
Objectives In this lesson, you will learn to: Define stacks
Stacks and Queues.
Queues Queues Queues.
Cinda Heeren / Geoffrey Tien
Stacks.
Stack and Queue APURBO DATTA.
Stacks Stack: restricted variant of list
Stacks Chapter 4.
Stack.
CMSC 341 Lecture 5 Stacks, Queues
Queues.
CSC 143 Queues [Chapter 7].
Stacks and Queues 1.
Stacks Data structure Elements added, removed from one end only
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Jordi Cortadella and Jordi Petit Department of Computer Science
Stacks and Queues CSE 373 Data Structures.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Getting queues right … finally (?)
Presented by : Aman Gupta PGT CS KV No.1, Narimedu, Madurai
Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Presentation transcript:

Lists, Stacks and Queues

More complete list ADT struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor ~List(); // destructor List& operator=(const List& list); // assignment operator // plus other overloaded operators bool empty() const; // boolean function void add(double x); // add to the head void delete(); // delete the head and get the head element double head() const; // get the head element bool search(double x); // search for a given x void insert(double x); // insert x in a sorted list void delete(double x); // delete x in a sorted list void addEnd(double x); // add to the end void deleteEnd(); // delete the end and get the end element double end(); // get the element at the end void display() const; // output int length() const; // count the number of elements private: Node* head; More complete list ADT

list ADT (a general list) class List { public: List(); // constructor List(const List& list); // copy constructor ~List(); // destructor bool empty() const; // boolean function double head() const; // get the head element void add(double x); // add to the head void delete(); // delete the head element void display() const; // output private: … }; Or to define one function: Double delete(); Which deletes and returns the head element.

list ADT (a sorted list) class List { public: List(); // constructor List(const List& list); // copy constructor ~List(); // destructor bool empty() const; // boolean function double head(); const; // get the first element void insert(double x); // insert x in a sorted list void delete(double x); // delete x in a sorted list void display() const; // output bool search(double x); // search for a given x private: … };

Implementation and Efficiency Static array Dynamic array Linked lists with and without ‘dummy head’ tricks Efficiency Insertion  construction, composition Deletion  destruction, decomposition Search  application, usage

Advantages and disadvantages of different implementations of a list Static array Dynamic array Linked list Insertion Deletion Search

Stacks

Stack Overview Stack ADT Basic operations of stack Pushing, popping etc. Implementations of stacks using array linked list

Stack A stack is a list in which insertion and deletion take place at the same end This end is called top The other end is called bottom Stacks are known as LIFO (Last In, First Out) lists. The last element inserted will be the first to be retrieved

Push and Pop Primary operations: Push and Pop Push Pop Add an element to the top of the stack Pop Remove the element at the top of the stack top empty stack A top push an element top push another A B top pop A

Implementation of Stacks Any list implementation could be used to implement a stack Arrays (static: the size of stack is given initially) Linked lists (dynamic: never become full) We will explore implementations based on arrays and linked list

Stack ADT class Stack { public: Stack(); // constructor Stack(const Stack& stack); // copy constructor ~Stack(); // destructor bool empty() const; double top() const; // keep the stack unchanged void push(const double x); double pop(); // change the stack … // optional void display() const; bool full() const; private: }; ‘physical’ constructor/destructor inspection, access headElement addHead deleteHead update, ‘logical’ constructor/destructor, composition/decomposition Compare with List, see that it’s ‘operations’ that define the type! ‘stack’ is the same as our ‘unsorted’ list operating at the head 

Using Stack result int main() { Stack stack; stack.push(5.0); stack.display(); cout << "Top: " << stack.top() << endl; stack.pop(); while (!stack.empty()) stack.pop(); return 0; } result

Stack using linked lists struct Node{ public: double data; Node* next; }; class Stack { Stack(); // constructor Stack(const Stack& stack); // copy constructor ~Stack(); // destructor bool empty() const; double top() const; // keep the stack unchanged void push(const double x); double pop(); // change the stack bool full(); // unnecessary for linked lists void display() const; private: Node* top;

Push (addHead), Pop (deleteHead) void List::addHead(int newdata){ Nodeptr newPtr = new Node; newPtr->data = newdata; newPtr->next = head; head = newPtr; } From ‘addHead’ to ‘push’ void Stack::push(double x){ Node* newPtr = new Node; newPtr->data = x; newPtr->next = top; top = newPtr; }

Stack using arrays double top(); class Stack { public: Stack(int size = 10); Stack(const Stack& stack); ~Stack() { delete[] values; } bool empty() { return (top == -1); } double top(); void push(const double x); double pop(); bool full() { return (top == size); } void display(); private: int size; // max stack size = size - 1 int top; // current top of stack double* values; // element array };

Attributes of Stack Operations of Stack size: the max size of stack top: the index of the top element of stack values: point to an array which stores elements of stack Operations of Stack empty: return true if stack is empty, return false otherwise full: return true if stack is full, return false otherwise top: return the element at the top of stack push: add an element to the top of stack pop: delete the element at the top of stack display: print all the data in the stack

Stack constructor Allocate a stack array of size. By default, size = 10. Initially top is set to -1. It means the stack is empty. When the stack is full, top will have its maximum value, i.e. size – 1. Stack::Stack(int size /*= 10*/) { values = new double[size]; top = -1; maxTop = size - 1; } Although the constructor dynamically allocates the stack array, the stack is still static. The size is fixed after the initialization.

void push(const double x); Push an element onto the stack Note top always represents the index of the top element. After pushing an element, increment top. void Stack::push(const double x) { if (full()) // if stack is full, print error cout << "Error: the stack is full." << endl; else values[++top] = x; }

double pop() Pop and return the element at the top of the stack Don’t forgot to decrement top double Stack::pop() { if (empty()) { //if stack is empty, print error cout << "Error: the stack is empty." << endl; return -1; } else { return values[top--];

double top() Return the top element of the stack Unlike pop, this function does not remove the top element double Stack::top() { if (empty()) { cout << "Error: the stack is empty." << endl; return -1; } else return values[top];

void print() Print all the elements void Stack::print() { cout << "top -->"; for (int i = top; i >= 0; i--) cout << "\t|\t" << values[i] << "\t|" << endl; cout << "\t|---------------|" << endl; }

A better variant: A better approach is to let position 0 be the bottom of the stack An integer to indicate the top of the stack (Stack.h) [7] ? [6] [5] 77 [4] 121 [3] 64 [2] 234 [1] 51 [0] [7] ? [6] 95 [5] 77 [4] 121 [3] 64 [2] 234 [1] 51 [0] 29 top = [7] 80 [6] 95 [5] 77 [4] 121 [3] 64 [2] 234 [1] 51 [0] 29 [7] ? [6] 95 [5] 77 [4] 121 [3] 64 [2] 234 [1] 51 [0] 29 top = top = top = Push 95 Push 80 Pop 23

Stack Application: base conversion Convert a base ten number into a base two number. 2 26 13 … 6 1 3 Example: 26  11010 24

Stack stack(); while (D is not zero) { push the remainder of D D  D/2 } while (not empty stack) pop

Stack.h, Stack.cpp and BaseConversion.cpp Can be written easily using recursion (do it yourself)

Recursive version: convert(D) if D is zero, stop else push(the remainder) convert(D/2) while (not empty stack) pop

Stack Application: Balancing Symbols To check that every right brace, bracket, and parentheses must correspond to its left counterpart e.g. [( )] is legal, but [( ] ) is illegal How? Need to memorize Use a counter, several counters, each for a type of parenthesis …

Balancing Symbols using a stack Algorithm (1)   Make an empty stack. (2)   Read characters until end of file i.    If the character is an opening symbol, push it onto the stack ii.   If it is a closing symbol, then if the stack is empty, report an error iii.  Otherwise, pop the stack. If the symbol popped is not the corresponding opening symbol, then report an error (3)   At end of file, if the stack is not empty, report an error (paren.cpp)

Stack Application: postfix, infix expressions and calculator Evaluating Postfix expressions a b c * + d e * f + g * + Operands are in a stack Converting infix to postfix a+b*c+(d*e+f)*g  a b c * + d e * f + g * + Operators are in a stack Calculator Adding more operators …

Infix, prefix, and postfix Consider the arithmetic statement in the assignment statement: x = a * b + c This is "infix" notation: the operators are between the operands Compiler must generate machine instructions 1. LOAD a 2. MULT b 3. ADD c 4. STORE x 31

Prefix : Operators come before the operands Examples Infix RPN (Postfix) Prefix A + B A B + + A B A * B + C A B * C + + * A B C A * (B + C) A B C + * * A + B C A - (B - (C - D)) A B C D--- -A-B-C D A - B - C - D A B-C-D- ---A B C D Prefix : Operators come before the operands 32

RPN or Postfix Notation Reverse Polish Notation (RPN) = Postfix notation Most compilers convert an expression in infix notation to postfix The operators are written after the operands So “a * b + c” becomes “a b * c +” Easier for compiler to work on loading and operation of variables Advantage: expressions can be written without parentheses 33

Evaluating RPN Expressions (Similar to Compiler Operations) Example: 2 3 4 + 5 6 - - * 2 7 5 6 - - * 2 7 -1 - * 2 8 * 16

An expression is a list of ‘characters’ or more generally ‘tokens’ or ‘strings while (not the end of the expression) do { get the current ‘token’ if it is operand, store it …  a stack if it is operator, get back operands Evaluate store the result move to the next } Use a Stack to store ‘operands’  a stack!

while (not the end of the expression) { get the current ‘token’ if it is operand, push; else if it is operator, pop (one operand); pop (another operand); evaluate; push (the result); move to the next }

list  expression stack  empty while (notempty(list)) do { c = head(list); if (c == ‘operand’) push(c,stack) else if (c == ‘operator) operand2 = pop(stack); operand1 = pop(stack); res=evaluate(c,operand1,operand2); push(res,stack); list  delete(list) } Further refine: - operators: +, -, *, / - operands: … - evaluate: …

More object-oriented: List list(expression); Stack stack(); while (list.notempty) do { c = list.head(); if (c == ‘operand’) stack.push(c) else if (c == ‘operator) operand2 = stack.pop; operand1 = stack.pop; res=evaluate(c,operand1,operand2); stack.push; list.delete(); } Further refine: - operators: +, -, *, / - operands: … - evaluate: …

(end of strings) 2 4 * 9 5 + - Push 2 onto the stack 4 * 9 5 + - Pop 4 and 2 from the stack , multiply, and push the result 8 back 8 9 5 + - Push 9 onto the stack 9 8 5 + - Push 5 onto the stack 5 9 8 + - Pop 5 and 9 from the stack, add, and push the result 14 back 14 8 - Pop 14 and 8 from the stack, subtract, and push the result -6 back -6 (end of strings) Value of expression is on top of the stack -6

Stack Application: function calls and recursion int fac(int n){ int product; if(n <= 1) product = 1; else product = n * fac(n-1); return product; } void main(){ int number; cout << "Enter a positive integer : " << endl;; cin >> number; cout << fac(number) << endl;

Assume the number typed is 3. Tracing the program … Assume the number typed is 3. fac(3): has the final returned value 6 3<=1 ? No. product3 = 3*fac(2) product3=3*2=6, return 6, fac(2): 2<=1 ? No. product2 = 2*fac(1) product2=2*1=2, return 2, fac(1): 1<=1 ? Yes. return 1

Call is to ‘push’ and return is to ‘pop’! fac(1) prod1=1 fac(2) prod2=2*fac(1) fac(3) prod3=3*fac(2) Actually for any function call, it is a stack!

Let the system do the ‘stack’ for you! convert(D) if D is zero, stop else push(the remainder) convert(D/2) while (not empty stack) pop and display Stack stack(); while (D is not zero) { push the remainder of D D  D/2 } while (not empty stack) pop The same! convert(D) if D is zero, stop else convert(D/2) display the remainder of D

Static and dynamic objects ‘static variables’ are from a Stack ‘dynamic variables’ are from a heap (seen later …)

Array versus linked list implementations push, pop, top are all constant-time operations in both array and linked list implementation For array implementation, the operations are performed in very fast constant time Often we use ‘array’ implementations for Stacks

Queues A queue is a waiting line – seen in daily life A line of people waiting for a bank teller A line of cars at a toll both "This is the captain, we're 5th in line for takeoff"

Queue A queue is also a list. However, insertion is done at one end, while deletion is performed at the other end. It is “First In, First Out (FIFO)” order. Like customers standing in a check-out line in a store, the first customer in is the first customer served.

Queue Overview Queue ADT Basic operations of queue Enqueuing, dequeuing etc. Implementation of queue Linked list Array

Enqueue and Dequeue Primary queue operations: Enqueue and Dequeue Like check-out lines in a store, a queue has a front and a rear. Enqueue – insert an element at the rear of the queue Dequeue – remove an element from the front of the queue Insert (Enqueue) Remove (Dequeue) front rear

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

Queue ADT class Queue { public: Queue(); Queue(const Queue& queue); bool empty(); double front(); // optional: front inspection (no queue change) void enqueue(double x); double dequeue(); // optional void display(void); bool full(); private: … }; ‘physical’ constructor/destructor ‘logical’ constructor/destructor Yes, ‘front’ like ‘top’ in a stack is a redundant definition, but usually ‘front’ is less useful in a queue application than the ‘top’ in a stack

Using Queue int main(void) { Queue queue; cout << "Enqueue 5 items." << endl; for (int x = 0; x < 5; x++) queue.enqueue(x); cout << "Now attempting to enqueue again..." << endl; queue.enqueue(5); queue.print(); double value; value=queue.dequeue(); cout << "Retrieved element = " << value << endl; queue.enqueue(7); return 0; }

Queue using linked lists Struct Node { double data; Node* next; } class Queue { public: Queue(); Queue(const Queue& queue); ~Queue(); bool empty(); void enqueue(double x); double dequeue(); // bool full(); // optional void print(void); private: Node* front; // pointer to front node Node* rear; // pointer to last node int counter; // number of elements };

Implementation of some online member functions … class Queue { public: Queue() { // constructor front = rear = NULL; counter = 0; } ~Queue() { // destructor double value; while (!empty()) dequeue(value); bool empty() { if (counter) return false; else return true; void enqueue(double x); double dequeue(); // bool full() {return false;}; void print(void); private: Node* front; // pointer to front node Node* rear; // pointer to last node int counter; // number of elements, not compulsary };

Enqueue (addEnd) 8 5 8 5 void Queue::enqueue(double x) { Node* newNode = new Node; newNode->data = x; newNode->next = NULL; if (empty()) { front = newNode; } else { rear->next = newNode; rear = newNode; counter++; rear 8 5 rear 8 5 newNode

Dequeue (deleteHead) 3 8 5 8 5 double Queue::dequeue() { double x; if (empty()) { cout << "Error: the queue is empty." << endl; exit(1); // return false; } else { x = front->data; Node* nextNode = front->next; delete front; front = nextNode; counter--; return x; front 3 8 5 8 5 front

Printing all the elements void Queue::print() { cout << "front -->"; Node* currNode = front; for (int i = 0; i < counter; i++) { if (i == 0) cout << "\t"; else cout << "\t\t"; cout << currNode->data; if (i != counter - 1) cout << endl; else cout << "\t<-- rear" << endl; currNode = currNode->next; }

Queue using Arrays 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. front rear Enqueue(3) 3 Enqueue(6) 6 Enqueue(9) 9

Naïve way (cont’d) When dequeuing, the front index is fixed, and the element at the front the queue is removed. Move all the elements after it by one position. (Inefficient!!!) rear rear rear = -1 6 9 9 front front front Dequeue() Dequeue() Dequeue()

A better way When enqueued, the rear index moves forward. When dequeued, the front index also moves forward by one element (front) XXXXOOOOO (rear) OXXXXOOOO (after 1 dequeue, and 1 enqueue) OOXXXXXOO (after another dequeue, and 2 enqueues) OOOOXXXXX (after 2 more dequeues, and 2 enqueues) The problem here is that the rear index cannot move beyond the last element in the array.

Using Circular Arrays 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)) How to detect an empty or full queue, using a circular array algorithm? Use a counter of the number of elements in the queue.

full() is not essential, can be embedded class Queue { public: Queue(int size = 10); // constructor Queue(const Queue& queue); // not necessary! ~Queue() { delete[] values; } // destructor bool empty(void); void enqueue(double x); // or bool enqueue(); double dequeue(); bool full(); void print(void); private: int front; // front index int rear; // rear index int counter; // number of elements int maxSize; // size of array queue double* values; // element array }; full() is not essential, can be embedded

Attributes of Queue Operations of Queue front/rear: front/rear index counter: number of elements in the queue maxSize: capacity of the queue values: point to an array which stores elements of the queue Operations of Queue empty: return true if queue is empty, return false otherwise full: return true if queue is full, return false otherwise enqueue: add an element to the rear of queue dequeue: delete the element at the front of queue print: print all the data

Queue constructor Queue(int size = 10) Allocate a queue array of size. By default, size = 10. front is set to 0, pointing to the first element of the array rear is set to -1. The queue is empty initially. Queue::Queue(int size /* = 10 */) { values = new double[size]; maxSize = size; front = 0; rear = -1; counter = 0; }

Empty & Full Since we keep track of the number of elements that are actually in the queue: counter, it is easy to check if the queue is empty or full. bool Queue::empty() { if (counter==0) return true; else return false; } bool Queue::full() { if (counter < maxSize) return false; else return true;

Enqueue Or ‘bool’ if you want void Queue::enqueue(double x) { if (full()) { cout << "Error: the queue is full." << endl; exit(1); // return false; } else { // calculate the new rear position (circular) rear = (rear + 1) % maxSize; // insert new item values[rear] = x; // update counter counter++; // return true;

Dequeue double Queue::dequeue() { double x; if (empty()) { cout << "Error: the queue is empty." << endl; exit(1); // return false; } else { // retrieve the front item x = values[front]; // move front front = (front + 1) % maxSize; // update counter counter--; // return true; return x;

Printing the elements void Queue::print() { cout << "front -->"; for (int i = 0; i < counter; i++) { if (i == 0) cout << "\t"; else cout << "\t\t"; cout << values[(front + i) % maxSize]; if (i != counter - 1) cout << endl; else cout << "\t<-- rear" << endl; }

Using Queue int main(void) { Queue queue; cout << "Enqueue 5 items." << endl; for (int x = 0; x < 5; x++) queue.enqueue(x); cout << "Now attempting to enqueue again..." << endl; queue.enqueue(5); queue.print(); double value; value=queue.dequeue(); cout << "Retrieved element = " << value << endl; queue.enqueue(7); return 0; }

Results Queue implemented using linked list will be never full! based on array based on linked list Queue implemented using linked list will be never full!

Queue applications When jobs are sent to a printer, in order of arrival, a queue. Customers at ticket counters …