ADTs: Stacks and Queues
|
|
- Willis Cummings
- 5 years ago
- Views:
Transcription
1 Introduction to the Stack ADTs: Stack: a data structure that holds a collection of elements of the same type. - The elements are accessed according to LIFO order: last in, first out - No random access to other elements Examples: - plates in a cafeteria - bangles... Applications : An "undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack. o o o Undo/Redo stacks in Excel or Word. Compiler's syntax check for matching braces is implemented by using stack. Reverse a word. You push a given word to stack - letter by letter - and then pop letters from the stack. Back/Forward stacks on browsers. Support for recursion Fall 2018 Husain Gholoom Lecturer in Computer Science Page 1
2 Stack Operations - Operations: - push: add a value onto the top of the stack make sure it s not full first. - pop: remove (and return) the value from the top of the stack make sure it s not empty first. - peek() Return the element at the top of the stack without removing it, if the stack is not empty. - size() Return the number of elements in the stack. - isfull: true if the stack is currently full, i.e., has no more space to hold additional elements - isempty: true if the stack currently contains no elements - These operations should take constant time: O(1). - makeempty: removes all the elements ( This may take longer than constant time ) Stack Terms Stack overflow: - trying to push an item onto a full stack Stack underflow. - trying to pop an item from an empty stack Stack illustrated Fall 2018 Husain Gholoom Lecturer in Computer Science Page 2
3 Stack Application: Postfix notation Postfix notation is another way of writing arithmetic expressions. We normally use infix: the operator is between the operands In postfix notation, the operator is written after the two operands. infix: 2+5 postfix: Expressions are evaluated from left to right. Precedence rules and parentheses are never needed!! Simple Example : Assume that A = 4, B = 3, C = 2, D = 1 find the postfix notations then find the answer for the following infix : Infix Postfix notation Answer A + B A * B + C A * (B + C) A - (B - (C - D)) A - B - C - D 5 + ((1 + 2) 4) 3 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 3
4 Postfix notation: using a stack Evaluation from left to right: push operands for operator: pop two values, perform operation Convert the following infix to postfix and evaluate using ( ) * ( 7 2 ) Fall 2018 Husain Gholoom Lecturer in Computer Science Page 4
5 Evaluate Postfix Expression algorithm Using a stack: WHILE more input items exist get next item from input IF item is an operand stack.push(item) ELSE operand2 = stack.pop() operand1 = stack.pop() Compute result using item as operator stack.push(result) end WHILE result = stack.pop() Implementing a Stack Class Array implementation: - fixed size or use dynamic arrays - fixed arrays: size doesn t change - dynamic arrays: can resize as needed in pop Linked List - grow and shrink in size as needed Fall 2018 Husain Gholoom Lecturer in Computer Science Page 5
6 A static stack class class IntStack private: int *stackarray; // Pointer to the stack array int stacksize; // The stack size (will not change) int top; // Index to the top of the stack public: // Constructor IntStack(int); // Destructor ~IntStack(); // Stack operations void push(int); int pop(); bool isfull() const; bool isempty() const; void makeempty(); This implementation uses a dynamic stack, but it never resizes it once initialized. But it is capable of making a fixed size stack of any size. Fall 2018 Husain Gholoom Lecturer in Computer Science Page 6
7 A static stack class: functions //*********************************************** // Constructor * // This constructor creates an empty stack. The * // size parameter is the size of the stack. * //*********************************************** IntStack::IntStack(int size) stackarray = new int[size]; // dynamic alloc stacksize = size; // save for reference top = -1; // empty //*********************************************** // Destructor * //*********************************************** IntStack::~IntStack() delete [] stackarray; A static stack class: push //************************************************* // Member function push pushes the argument onto * // the stack. * //************************************************* void IntStack::push(int num) assert(!isfull()); top++; stackarray[top] = num; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 7
8 A static stack class: pop //**************************************************** // Member function pop pops the value at the top * // of the stack off, and returns it. * //***************************************************** int IntStack::pop() assert(!isempty()); int num = stackarray[top]; top--; return num; A static stack class: functions //*************************************************** // Member function isfull returns true if the stack * // is full, or false otherwise. * //**************************************************** bool IntStack::isFull() const return (top == stacksize - 1); //**************************************************** // Member function isempty returns true if the stack * // is empty, or false otherwise. * //**************************************************** bool IntStack::isEmpty() const return (top == -1); Fall 2018 Husain Gholoom Lecturer in Computer Science Page 8
9 A static stack class: makeempty //**************************************************** // Member function makeempty makes the stack an * // empty stack. * //***************************************************** void IntStack::makeEmpty() top = -1; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 9
10 A Stack Implementation using Arrays IntStack.h /* * stack.h * * Author: hag10 */ #ifndef STACK_H_ #define STACK_H_ class IntStack private: int *stackarray; // Pointer to the stack array int stacksize; // The stack size int top; // Indicates the top of the stack public: // Constructor IntStack(int); ; // Destructor ~IntStack(); // Stack operations void push(int); void pop(int &); bool isfull() const; bool isempty() const; #endif /* STACK_H_ */ Fall 2018 Husain Gholoom Lecturer in Computer Science Page 10
11 IntStack.cpp /* * stack.cpp * * Author: hag10 */ // Implementation file for the IntStach class #include <iostream> #include "IntStack.h" using namespace std; //*********************************************** // Constructor * // This constructor creates an empty stack. The * // size parameter is the size of the stack. * //*********************************************** IntStack::IntStack(int size) stackarray = new int[size]; stacksize = size; top = -1; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 11
12 IntStack.cpp ( continued ) //*********************************************** // Destructor * //*********************************************** IntStack::~IntStack() delete [] stackarray; //************************************************* // Member function push pushes the argument onto * // the stack. * //************************************************* void IntStack::push(int num) if (isfull()) cout << "The stack is full.\n"; else top++; stackarray[top] = num; //**************************************************** // Member function pop pops the value at the top * // of the stack off, and copies it into the variable * // passed as an argument. * //**************************************************** void IntStack::pop(int &num) if (isempty()) cout << "The stack is empty.\n"; else num = stackarray[top]; top--; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 12
13 IntStack.cpp ( continued ) //*************************************************** // Member function isfull returns true if the stack * // is full, or false otherwise. * //*************************************************** bool IntStack::isFull() const bool status; if (top == stacksize - 1) status = true; else status = false; return status; //**************************************************** // Member function isempty returns true if the stack * // is empty, or false otherwise. * //**************************************************** bool IntStack::isEmpty() const bool status; if (top == -1) status = true; else status = false; return status; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 13
14 IntStackDriver.cpp /* * stackdriver.cpp * * Author: hag10 */ // This program demonstrates the IntStack class. #include <iostream> #include "Stack.h" using namespace std; int main() int catchvar; // To hold values popped off the stack // Define a stack object to hold 5 values. IntStack stack(5); // Push the values 5, 10, 15, 20, and 25 onto the stack. cout << "Pushing 5\n"; stack.push(5); cout << "Pushing 10\n"; stack.push(10); cout << "Pushing 15\n"; stack.push(15); cout << "Pushing 20\n"; stack.push(20); cout << "Pushing 25\n"; stack.push(25); cout << "Pushing 25\n"; stack.push(25); // Pop the values off the stack. cout << "Removing...\n"; stack.pop(catchvar); cout << catchvar << endl; stack.pop(catchvar); cout << catchvar << endl; stack.pop(catchvar); cout << catchvar << endl; stack.pop(catchvar); cout << catchvar << endl; stack.pop(catchvar); cout << catchvar << endl; return 0; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 14
15 Sample Run Pushing 5 Pushing 10 Pushing 15 Pushing 20 Pushing 25 Removing What happens if you add the following statements cout << "Pushing 30\n"; stack.push(30); cout << "Pushing 35\n"; stack.push(35); cout << "Pushing 40\n"; stack.push(40); or stack.pop(catchvar); cout << catchvar << endl; stack.pop(catchvar); cout << catchvar << endl; stack.pop(catchvar); cout << catchvar << endl; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 15
16 Introduction to the Queue Queue: a data structure that holds a collection of elements of the same type. - The elements are accessed according to FIFO order: first in, first out - No random access to other elements Examples: - One of the best examples of queue is print jobs sent to a printer. add a new print job to the queue (enqueue). The dequeue operation starts printing job starts. While printing, more jobs are added to the Q. When the printer finishes a current job, it pulls the next job from the Q and starts printing. Continuing this process until the Q is empty Other Examples: - People in line at a theatre box office - A line of people waiting for a bank teller - A line of cars at a toll both A Conceptual View of a Queue Fall 2018 Husain Gholoom Lecturer in Computer Science Page 16
17 Queue Operations Operations: o enqueue: add a value onto the rear of the queue (the end of the line) make sure it s not full first. o dequeue: remove a value from the front of the queue (the front of the line) Next! make sure it s not empty first. peek() Return the element of the queue without removing it, if the queue is not empty. size() Return the number of elements in the queue. o isfull: true if the queue is currently full, i.e., has no more space to hold additional elements o isempty: true if the queue currently contains no elements These operations should take constant time: O(1) o makeempty: removes all the elements This may take longer than constant time. Fall 2018 Husain Gholoom Lecturer in Computer Science Page 17
18 Queue illustrated int item; q.enqueue(2): q.enqueue(3); q.enqueue(5); item = q.dequeue(); //item is 2 item = q.dequeue(); //item is 3 q.enqueue(10); Note: front and rear are variables used by the implementation to carry out the operations Fall 2018 Husain Gholoom Lecturer in Computer Science Page 18
19 Queue implemented Just like stacks, queues can be implemented using arrays (fixed size, or resizing dynamic arrays) or linked lists (dynamic queues). The previous illustration assumed we were using an array to implement the queue When an item was dequeued, the items were NOT shifted up to fill the slot vacated by dequeued item. why not? Instead, both front and rear indices move in the array. Queue implemented : problem: end of the array When front and rear indices move in the array: Problem: rear hits end of array quickly Solution: wrap index around to front of array front rear rear front rear front Fall 2018 Husain Gholoom Lecturer in Computer Science Page 19
20 Queue implemented : solution: wraparound To wrap the index back to the front of the array, use this code to increment rear during enqueue: if (rear == queuesize-1) rear = 0; else rear = rear+1; This code is equivalent to the following rear = (rear + 1) % queuesize; Do the same for advancing front index. Now, how do we know if the queue is empty or full? Queue implemented : problem: detecting full and empty queues When rear==front, is it full, or size==1? - Some implementations offset front or rear by 1. An easy solution: - Use a counter variable to keep track of the total number of items in the queue. enqueue: numitems++ dequeue: numitems-- isempty is true when numitems == 0 isfull is true when numitems == queuesize Queue implemented In the implementation that follows: the queue is a dynamically allocated array, whose size does not change front and rear are initialized to -1. If the queue is not empty: - rear is the index of the last item that was enqueued. - front+1 is the index of the next item to be dequeued. numitems: how many items are in the queue queuesize: the size of the array Fall 2018 Husain Gholoom Lecturer in Computer Science Page 20
21 A static queue class class IntQueue private: int *queuearray; // Points to the queue array int queuesize; // The queue size int front; // Subscript of the queue front int rear; // Subscript of the queue rear int numitems; // Number of items in the queue public: // Constructors/Destructor IntQueue(int); ~IntQueue(); ; // Queue operations void enqueue(int); int dequeue(); bool isempty() const; bool isfull() const; void makeempty(); Fall 2018 Husain Gholoom Lecturer in Computer Science Page 21
22 A static queue class: functions A static queue class: functions //****************************************************** // Creates an empty queue of a specified size. * //****************************************************** IntQueue::IntQueue(int s) queuearray = new int[s]; // dynamic alloc queuesize = s; // save for reference front = -1; // set up bookkeeping rear = -1; numitems = 0; //****************************************************** // Destructor * //****************************************************** IntQueue::~IntQueue() delete [] queuearray; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 22
23 A static queue class: enqueue //****************************************************** // Enqueue inserts a value at the rear of the queue. * //****************************************************** Void IntQueue::enqueue(int num) assert(!isfull()); // Calculate the new rear position if (rear == queuesize-1) rear = 0; else rear = rear+1; // Insert new item queuearray[rear] = num; // Update item count numitems++; A static queue class: dequeue //****************************************************** // Dequeue removes the value at the front of the * // queue and copies t into num. * //****************************************************** int IntQueue::dequeue() assert(!isempty()); // Move front front = (front + 1) % queuesize; // Update item count numitems--; // Retrieve the front item return queuearray[front]; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 23
24 A static queue class: functions //****************************************************** // isempty returns true if the queue is empty * //****************************************************** bool IntQueue::isEmpty() const return (numitems == 0); //****************************************************** // isfull returns true if the queue is full * //****************************************************** bool IntQueue::isFull() const return (numitems == queuesize); //***************************************************** // makeempty makes the stack empty * //***************************************************** void IntQueue::makeEmpty() front = - 1; rear = - 1; numitems = 0; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 24
25 Array vs Linked List implementations Both are very fast (O(1)). Array may be faster (no dynamic allocation) Static arrays: - must anticipate maximum size - wasted space: entire array is allocated, even if using small portion Dynamic arrays (resize when full): - resizing takes time (copying all the elements) - resizing requires memory that is three times what is needed to store the elements at that time Linked List: - code is actually simpler than array with resizing, especially for queues. - space used by elements is always proportional to number of elements (only wasted space is for the pointers) Summary: - array implementation is probably better for small objects. - linked list is probably better for large objects if space is scarce or copying is expensive (resizing) Fall 2018 Husain Gholoom Lecturer in Computer Science Page 25
26 Queue Implementation using Arrays Queue.h /* * Queue.h * * Author: hag10 */ #ifndef QUEUE_H_ #define QUEUE_H_ class IntQueue private: int *queuearray; // Points to the queue array int queuesize; // The queue size int front; // Subscript of the queue front int rear; // Subscript of the queue rear int numitems; // Number of items in the queue public: // Constructor IntQueue(int); ; // Destructor ~IntQueue(); // Queue operations void enqueue(int); void dequeue(int &); bool isempty() ; bool isfull() ; #endif /* QUEUE_H_ */ Fall 2018 Husain Gholoom Lecturer in Computer Science Page 26
27 Queue.cpp /* * Queue.cpp * * Author: hag10 */ // Implementation file for the IntQueue class #include <iostream> #include "IntQueue.h" using namespace std; //*************************************************************** // This constructor creates an empty queue of a specified size. * //*************************************************************** IntQueue::IntQueue(int s) queuearray = new int[s]; queuesize = s; front = -1; rear = -1; numitems = 0; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 27
28 IntQueue.cpp ( continued ) //*************************************************************** // Destructor * //*************************************************************** IntQueue::~IntQueue() delete [] queuearray; //*************************************************************** // Function enqueue inserts a value at the rear of the queue. * //*************************************************************** void IntQueue::enqueue(int num) if (isfull()) cout << "The queue is full.\n"; else // Calculate the new rear position if (rear == queuesize - 1) rear = 0; else rear = rear + 1; // Insert new item queuearray[rear] = num; // Update item count numitems++; cout<<num<<endl; //*************************************************************** // Function dequeue removes the value at the front of the queue * // and copies t into num. * //*************************************************************** void IntQueue::dequeue(int &num) if (isempty()) cout << "The queue is empty.\n"; else // Move front front = (front + 1) % queuesize; // Retrieve the front item num = queuearray[front]; // Update item count numitems--; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 28
29 IntQueue.cpp ( continued ) //*************************************************************** // isempty returns true if the queue is empty, otherwise false. * //*************************************************************** bool IntQueue::isEmpty() bool status; if (numitems!= 0) status = false; else status = true; return status; //*************************************************************** // isfull returns true if the queue is full, otherwise false. * //*************************************************************** bool IntQueue::isFull() bool status; if (numitems < queuesize) status = false; else status = true; return status; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 29
30 QueueDriver.cpp /* * QueueDriver.cpp * * Author: hag10 */ // This program demonstrates the IntQeue class #include <iostream> #include "Queue.h" using namespace std; int main() const int MAX_VALUES = 5; // Max number of values // Create an IntQueue to hold the values. IntQueue iqueue(max_values); // Enqueue a series of items. cout << "Enqueuing " << MAX_VALUES << " items...\n"; for (int x = 0; x < MAX_VALUES; x++) iqueue.enqueue(x); // Attempt to enqueue just one more item. cout << "\nnow attempting to enqueue again...\n"; iqueue.enqueue(max_values); // Deqeue and retrieve all items in the queue cout << "\ndequeuing : The values in the queue were:\n"; int value; while (!iqueue.isempty()) iqueue.dequeue(value); cout << value << endl; cout << endl << endl ; return 0; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 30
31 Sample Run Enqueuing 5 items Now attempting to enqueue again... The queue is full. The values in the queue were: Fall 2018 Husain Gholoom Lecturer in Computer Science Page 31
32 Stack in C++ STL Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only. The functions associated with stack are: empty() Returns whether the stack is empty Time Complexity : O(1) size() Returns the size of the stack Time Complexity : O(1) top() Returns a reference to the top most element of the stack Time Complexity : O(1) push(g) Adds the element g at the top of the stack Time Complexity : O(1) pop() Deletes the top most element of the stack Time Complexity : O(1) Fall 2018 Husain Gholoom Lecturer in Computer Science Page 32
33 Queue in Standard Template Library (STL) Queues are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. The functions supported by queue are : empty() Returns whether the queue is empty size() Returns the size of the queue front() Returns a reference to the first element of the queue back() Returns a reference to the last element of the queue push(g) Adds the element g at the end of the queue pop() Deletes the first element of the queue Fall 2018 Husain Gholoom Lecturer in Computer Science Page 33
34 Example : // CPP program to demonstrate working of STL stack #include <iostream> #include <stack> using namespace std; void showstack(stack<int> s) while (!s.empty()) cout << '\t' << s.top(); s.pop(); cout << '\n'; int main() stack<int> s; s.push(10); s.push(30); s.push(20); s.push(5); s.push(1); cout << "The stack is : "; showstack(s); cout << "\ns.size() : " << s.size(); cout << "\ns.top() : " << s.top(); cout << "\ns.pop() : "; s.pop(); showstack(s); return 0; The stack is : s.size() : 5 s.top() : 1 s.pop() : Fall 2018 Husain Gholoom Lecturer in Computer Science Page 34
35 Example // Queue in Standard Template Library (STL) #include <iostream> #include <queue> using namespace std; void showq(queue<int> gq) queue<int> g = gq; while (!g.empty()) cout << '\t' << g.front(); g.pop(); cout << '\n'; int main() queue<int> gquiz; gquiz.push(10); gquiz.push(20); gquiz.push(30); cout << "The queue gquiz is : "; showq(gquiz); cout << "\ngquiz.size() : " << gquiz.size(); cout << "\ngquiz.front() : " << gquiz.front(); cout << "\ngquiz.back() : " << gquiz.back(); cout << "\ngquiz.pop() : "; gquiz.pop(); showq(gquiz); return 0; The queue gquiz is : gquiz.size() : 3 gquiz.front() : 10 gquiz.back() : 30 gquiz.pop() : Fall 2018 Husain Gholoom Lecturer in Computer Science Page 35
Ch. 18: ADTs: Stacks and Queues. Abstract Data Type
Ch. 18: ADTs: Stacks and Queues CS 2308 Fall 2011 Jill Seaman Lecture 18 1 Abstract Data Type A data type for which: - only the properties of the data and the operations to be performed on the data are
More information! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:
Ch. 8: ADTs: Stacks and Queues Abstract Data Type A data type for which: CS 8 Fall Jill Seaman - only the properties of the data and the operations to be performed on the data are specific, - not concerned
More information! A data type for which: ! An ADT may be implemented using various. ! Examples:
Stacks and Queues Unit 6 Chapter 19.1-2,4-5 CS 2308 Fall 2018 Jill Seaman 1 Abstract Data Type A data type for which: - only the properties of the data and the operations to be performed on the data are
More informationIntroduction to the Stack. Stacks and Queues. Stack Operations. Stack illustrated. elements of the same type. Week 9. Gaddis: Chapter 18
Stacks and Queues Week 9 Gaddis: Chapter 18 CS 5301 Fall 2015 Jill Seaman Introduction to the Stack Stack: a data structure that holds a collection of elements of the same type. - The elements are accessed
More informationIntroduction to the Stack. Stacks and Queues. Stack Operations. Stack illustrated. Week 9. elements of the same type.
Stacks and Queues Week 9 Gaddis: Chapter 18 (8th ed.) Gaddis: Chapter 19 (9th ed.) CS 5301 Fall 2018 Jill Seaman Introduction to the Stack Stack: a data structure that holds a collection of elements of
More informationStacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016
Stacks Gaddis 18.1, 18.3 Molly A. O'Neil CS 2308 :: Spring 2016 The Stack ADT A stack is an abstract data type that stores a collection of elements of the same type The elements of a stack are accessed
More informationChapter 18: Stacks And Queues
Chapter 18: Stacks And Queues 18.1 Introduction to the Stack ADT Introduction to the Stack ADT Stack: a LIFO (last in, first out) data structure Examples: plates in a cafeteria return addresses for function
More informationQueues. Gaddis 18.4, Molly A. O'Neil CS 2308 :: Spring 2016
Queues Gaddis 18.4, 18.6 Molly A. O'Neil CS 2308 :: Spring 2016 The Queue ADT A queue is an abstract data type that stores a collection of elements of the same type The elements of a queue are accessed
More informationChapter 18: Stacks And Queues. Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 18: Stacks And Queues Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18.1 Introduction to
More informationChapter 18: Stacks And Queues
Chapter 18: Stacks And Queues 18.1 Introduction to the Stack ADT Introduction to the Stack ADT Stack a LIFO (last in, first out) data structure Examples plates in a cafeteria return addresses for function
More informationIntroduction to the Stack. Stacks and Queues. Stack Operations. Stack illustrated. elements of the same type. Week 9. Gaddis: Chapter 18
Stacks and Queues Week 9 Gaddis: Chapter 18 CS 5301 Spring 2017 Ji Seaman Introduction to the Stack Stack: a data structure that hods a coection of eements of the same type. - The eements are accessed
More informationCMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC
CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible
More informationCMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC
CMSC 341 Lecture 6 STL, Stacks, & Queues Based on slides by Lupoli, Dixon & Gibson at UMBC Templates 2 Common Uses for Templates Some common algorithms that easily lend themselves to templates: Swap what
More informationProgramming Abstractions
Programming Abstractions C S 1 0 6 B Cynthia Lee Today s Topics ADTs Stack Example: Reverse-Polish Notation calculator Queue Example: Mouse Events Stacks New ADT: Stack stack.h template
More informationLecture Data Structure Stack
Lecture Data Structure Stack 1.A stack :-is an abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example a deck of cards
More informationMore Group HW. #ifndef Stackh #define Stackh. #include <cstdlib> using namespace std;
More Group HW The following code is contained in the file ex1stck.h. Fill in the blanks with the C++ statement(s) that will correctly finish the method. Each blank may be filled in with more than one statement.
More informationCS24 Week 4 Lecture 2
CS24 Week 4 Lecture 2 Kyle Dewey Overview Linked Lists Stacks Queues Linked Lists Linked Lists Idea: have each chunk (called a node) keep track of both a list element and another chunk Need to keep track
More informationSTACKS AND QUEUES. Problem Solving with Computers-II
STACKS AND QUEUES Problem Solving with Computers-II 2 Stacks container class available in the C++ STL Container class that uses the Last In First Out (LIFO) principle Methods i. push() ii. iii. iv. pop()
More informationIV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard
IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two
More informationAn Introduction to Queues With Examples in C++
An Introduction to Queues With Examples in C++ Prof. David Bernstein James Madison University Computer Science Department bernstdh@jmu.edu Motivation Queues are very straightforward but are slightly more
More informationdouble d0, d1, d2, d3; double * dp = new double[4]; double da[4];
All multiple choice questions are equally weighted. You can generally assume that code shown in the questions is intended to be syntactically correct, unless something in the question or one of the answers
More informationAbstract Data Types 1
Abstract Data Types 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues 2 Abstract Data Types (ADTs) ADT is a set of objects together with a set of operations. Abstract in that implementation of operations
More informationAbstract Data Types. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University
Abstract Data Types CptS 223 Advanced Data Structures Larry Holder School of Electrical Engineering and Computer Science Washington State University 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues
More informationCS 106B Lecture 5: Stacks and Queues
CS 106B Lecture 5: Stacks and Queues Monday, July 3, 2017 Programming Abstractions Summer 2017 Stanford University Computer Science Department Lecturer: Chris Gregg reading: Programming Abstractions in
More informationLIFO : Last In First Out
Introduction Stack is an ordered list in which all insertions and deletions are made at one end, called the top. Stack is a data structure that is particularly useful in applications involving reversing.
More information// The next 4 functions return true on success, false on failure
Stacks and Queues Queues and stacks are two special list types of particular importance. They can be implemented using any list implementation, but arrays are a more practical solution for these structures
More informationDiscussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:
Discussion 2C Notes (Week 3, January 21) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Abstraction In Homework 1, you were asked to build a class called Bag. Let
More informationAbstract Data Types 1
Abstract Data Types 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues 2 Primitive vs. Abstract Data Types Primitive DT: programmer ADT: programmer Interface (API) data Implementation (methods) Data
More informationIntroduction to the C programming language
Introduction to the C programming language From C to C++: Stack and Queue Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 23, 2010 Outline 1 From struct to classes
More informationIntroduction to the C programming language
Introduction to the C programming language From C to C++: Stack and Queue Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 23, 2010 Outline 1 From struct to classes
More informationThe Stack and Queue Types
The Stack and Queue Types Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html 2 Programming Principle of the Day Do the simplest thing that could possibly work A good
More informationWentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.
Lecture 11 1 More Data Structures In this lecture we will use a linked list to implement two abstract data types (ADT) An ADT provides the interface, or what a data structure does We can then use code
More informationEEE2020 Data Structures and Algorithms Abstract Data Types: Stacks and Queues
EEE2020 Data Structures and Algorithms Abstract Data Types: Stacks and Queues W. Jinho Song School of Electrical & Electronic Engineering Yonsei University 1 Textbook Chapter and Objectives Textbook "Data
More informationProgramming Abstractions
Programming Abstractions C S 1 0 6 B Cynthia Lee Today s Topics HW Tips QT Creator dos & don ts ADTs Stack Example: Reverse-Polish Notation calculator Queue Event queues QT Creator A F E W W A R N I N
More informationUNIT-2 Stack & Queue
UNIT-2 Stack & Queue 59 13. Stack A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example a deck of cards
More informationl Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)
Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between
More informationChapter 7: Stacks. Exercises 7.2
hapter 7: Stacks Exercises 7.2 1. mytop == 0; myrray contains 3 elements: 10, 22, 37,?,? but note that only element 10 is considered to be in the stack. 2. mytop == 1; myrray contains 3 elements: 10, 9,
More informationStacks and Queues. Chapter 8 (Cont.)
Data Structures Dr Ahmed Rafat Abas Computer Science Dept, Faculty of Computer and Information, Zagazig University arabas@zu.edu.eg http://www.arsaliem.faculty.zu.edu.eg/ Stacks and Queues Chapter 8 (Cont.)
More informationDATA STRUCTURES AND ALGORITHMS LECTURE 08 QUEUES IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD
DATA STRUCTURES AND ALGORITHMS LECTURE 08 S IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD S ABSTRACT DATA TYPE An Abstract Queue (Queue ADT) is an abstract data type that emphasizes specific
More informationThe Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified.
The Stack ADT Stacks Set of objects in which the location an item is inserted and deleted is prespecified Stacks! Insert in order! Delete most recent item inserted! LIFO - last in, first out Stacks 2 The
More informationCSC 222: Computer Programming II. Spring 2004
CSC 222: Computer Programming II Spring 2004 Stacks and recursion stack ADT push, pop, top, empty, size vector-based implementation, library application: parenthesis/delimiter matching run-time
More informationObject Oriented Programming COP3330 / CGS5409
Object Oriented Programming COP3330 / CGS5409 Intro to Data Structures Vectors Linked Lists Queues Stacks C++ has some built-in methods of storing compound data in useful ways, like arrays and structs.
More information1 Short Answer (7 Points Each)
1 Short Answer (7 Points Each) 1. Given the following function, what operations will need to be overloaded in the class T for this code to compile? template T square(t n) { return n * n; } The
More informationData Structures using OOP C++ Lecture 9
Stack A stack is an ordered group of homogeneous items or elements. The removal of existing items and the addition of new items can take place only at the top of the stack. The stack may be considered
More informationADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )
ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) Unit - 2 By: Gurpreet Singh Dean Academics & H.O.D. (C.S.E. / I.T.) Yamuna Institute of Engineering & Technology, Gadholi What is a Stack? A stack is a
More informationEC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3
UNIT 3 LINEAR DATA STRUCTURES 1. Define Data Structures Data Structures is defined as the way of organizing all data items that consider not only the elements stored but also stores the relationship between
More informationA <Basic> C++ Course
A C++ Course 6 Fonctions et classes templates Julien Deantoni adapted from Jean-Paul Rigault courses 1 2 Pointers and references References vs. pointers References and pointers A reference must
More informationComputer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures
Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Linear Structures The structures we ve seen so far, Vectors/ArrayLists and linked lists, allow insertion and deletion of elements
More informationC++ For Science and Engineering Lecture 27
C++ For Science and Engineering Lecture 27 John Chrispell Tulane University Monday November 1, 2010 Classes and the This pointer Every C++ object has a curious pointer called this. If we want to extend
More informationCSCE 110 PROGRAMMING FUNDAMENTALS
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table
More informationMIDTERM EXAMINATION Spring 2010 CS301- Data Structures
MIDTERM EXAMINATION Spring 2010 CS301- Data Structures Question No: 1 Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the
More informationStacks and their Applications
Stacks and their Applications Lecture 23 Sections 18.1-18.2 Robb T. Koether Hampden-Sydney College Fri, Mar 16, 2018 Robb T. Koether Hampden-Sydney College) Stacks and their Applications Fri, Mar 16, 2018
More informationAssociate Professor Dr. Raed Ibraheem Hamed
Associate Professor Dr. Raed Ibraheem Hamed University of Human Development, College of Science and Technology Computer Science Department 2015 2016 1 What this Lecture is about: Stack Structure Stack
More informationLecture 4 Stack and Queue
Lecture 4 Stack and Queue Bo Tang @ SUSTech, Spring 2018 Our Roadmap Stack Queue Stack vs. Queue 2 Stack A stack is a sequence in which: Items can be added and removed only at one end (the top) You can
More informationHeaps. A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience)
Binary heap data structure Heaps A binary heap is a special kind of binary tree - has a restricted structure (must be complete) - has an ordering property (parent value is smaller than child values) Used
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Queues ArrayQueue Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 10, 2014 Abstract These lecture notes are meant to be looked
More informationProgramming Abstractions
Programming Abstractions C S 1 0 6 X Cynthia Lee Today s Topics ADTs Stack Example: Reverse-Polish Notation calculator Queue Example: Mouse Events Stacks New ADT: Stack stack.h template
More informationName CPTR246 Spring '17 (100 total points) Exam 3
Name CPTR246 Spring '17 (100 total points) Exam 3 1. Linked Lists Consider the following linked list of integers (sorted from lowest to highest) and the changes described. Make the necessary changes in
More informationCHAPTER 3 STACKS AND QUEUES. Iris Hui-Ru Jiang Fall 2008
HAPTER 3 STAKS AND QUEUES Iris Hui-Ru Jiang Fall 2008 2 ontents Templates in ++ Stack (LIFO) Queue (FIFO) Subtyping and Inheritance in ++ A Mazing Problem Evaluation of Expressions Readings hapter 3 ++
More informationCPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues
CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues Alan J. Hu (Slides borrowed from Steve Wolfman) Be sure to check course webpage! http://www.ugrad.cs.ubc.ca/~cs221 1 Lab 1 is available.
More informationCS 206 Introduction to Computer Science II
CS 206 Introduction to Computer Science II 07 / 26 / 2016 Instructor: Michael Eckmann Today s Topics Comments/Questions? Stacks and Queues Applications of both Priority Queues Michael Eckmann - Skidmore
More informationCMSC 341. Deques, Stacks and Queues 9/22/04 1
CMSC 341 Deques, Stacks and Queues 9/22/04 1 The Double-Ended Queue ADT The double ended queue is referred to as a Deque (rhymes with check ) Restricted List add to the end remove from the end add to the
More informationStacks and Queues. Stack - Abstract Data Type. Stack Applications. Stack - Abstract Data Type - C Interface
Stacks and Queues Stack - Abstract Data Type. Stacks and queues ubiquitous -structure in computing. Part of many important algorithms. Good example of abstract types. Good example to practice programming
More informationAbstract Data Types. Abstract Data Types
Abstract Data Types Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria Wolfgang.Schreiner@risc.jku.at http://www.risc.jku.at Wolfgang Schreiner
More informationData Structures & Algorithm Analysis. Lecturer: Souad Alonazi
Data Structures & Algorithm Analysis Lec(3) Stacks Lecturer: Souad Alonazi What is a stack? Stores a set of elements in a particular order Stack principle: LAST IN FIRST OUT = LIFO It means: the last element
More information06-Oct-18. Lecture No.05. Infix to Postfix A + B A B (A + B)*(C D ) A B + C D * A B * C D + E/F A B C*D E F/+
Lecture No.05 Infix to Postfix Infix Postfix A + B A B + 12 + 60 23 12 60 + 23 (A + B)*(C D ) A B + C D * A B * C D + E/F A B C*D E F/+ 1 Infix to Postfix Note that the postfix form an expression does
More informationCMSC 341 Lecture 7. Announcements. Proj 2 up Project Preview tonight and tomorrow
CMSC 341 Lecture 7 Announcements Proj 2 up Project Preview tonight and tomorrow 1 Comparing Performance Linear S Linked D Linked Cursor constructor O(1) O(1) O(1) O(1) find O(n) O(n) O(n) O(n) findprev
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College November 22, 2017 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates
More informationCSEN 301 Data Structures and Algorithms
CSEN 301 Data Structures and Algorithms Lecture 5: Queues: Implementation and usage Prof. Dr. Slim Abdennadher slim.abdennadher@guc.edu.eg German University Cairo, Department of Media Engineering and Technology
More informationMore Data Structures (Part 1) Stacks
More Data Structures (Part 1) Stacks 1 Stack examples of stacks 2 Top of Stack top of the stack 3 Stack Operations classically, stacks only support two operations 1. push 2. pop add to the top of the stack
More informationQueue: Queue Representation: Basic Operations:
Queue: Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue) and the other is used to remove
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 10 Thomas Wies New York University Review Last class ML Outline Modules Sources: PLP, 3.3.4, 3.3.5, 3.8 McConnell, Steve. Code Complete, Second Edition,
More informationStacks and Queues. CSE Data Structures April 12, 2002
Stacks and Queues CSE 373 - Data Structures April 12, 2002 Readings and References Reading Section 3.3 and 3.4, Data Structures and Algorithm Analysis in C, Weiss Other References 12-Apr-02 CSE 373 - Data
More informationUniversity of Illinois at Urbana-Champaign Department of Computer Science. First Examination
University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section
More informationLists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50
Lists, Stacks, and Queues (Lists, Stacks, and Queues ) Data Structures and Programming Spring 2016 1 / 50 Abstract Data Types (ADT) Data type a set of objects + a set of operations Example: integer set
More information15. Stacks and Queues
COMP1917 15s2 15. Stacks and Queues 1 COMP1917: Computing 1 15. Stacks and Queues Reading: Moffat, Section 10.1-10.2 Overview Stacks Queues Adding to the Tail of a List Efficiency Issues Queue Structure
More informationStacks, Queues (cont d)
Stacks, Queues (cont d) CSE 2011 Winter 2007 February 1, 2007 1 The Adapter Pattern Using methods of one class to implement methods of another class Example: using List to implement Stack and Queue 2 1
More informationCPSC 221: Algorithms and Data Structures ADTs, Stacks, and Queues
CPSC 221: Algorithms and Data Structures ADTs, Stacks, and Queues Alan J. Hu (Slides borrowed from Steve Wolfman) Be sure to check course webpage! http://www.ugrad.cs.ubc.ca/~cs221 1 Lab 1 available very
More information[CS302-Data Structures] Homework 2: Stacks
[CS302-Data Structures] Homework 2: Stacks Instructor: Kostas Alexis Teaching Assistants: Shehryar Khattak, Mustafa Solmaz, Bishal Sainju Fall 2018 Semester Section 1. Stack ADT Overview wrt Provided Code
More informationSTACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:
STACKS A stack is a linear data structure for collection of items, with the restriction that items can be added one at a time and can only be removed in the reverse order in which they were added. The
More informationStacks and Queues 2017 年 4 月 27 日星期四. Thanks for CS106B of Stanford University. reading: Programming Abstractions in C++, Chapter
Stacks and Queues 2017 年 4 月 27 日星期四 Thanks for CS106B of Stanford University. reading: Programming Abstractions in C++, Chapter 5.2-5.3 Today's Topics Do we have to implement a Vector with an array? We
More informationCSE143 Exam with answers Problem numbering may differ from the test as given. Midterm #2 February 16, 2001
CSE143 Exam with answers Problem numbering may differ from the test as given. All multiple choice questions are equally weighted. You can generally assume that code shown in the questions is intended to
More informationSCJ2013 Data Structure & Algorithms. Queue. Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi
SCJ2013 Data Structure & Algorithms Queue Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi Course Objectives At the end of the lesson students are expected to be able to: Understand queue concepts and
More informationComputer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures
Computer Science 210 Data Structures Siena College Fall 2018 Topic Notes: Linear Structures The structures we ve seen so far, Vectors/ArrayLists and linked list variations, allow insertion and deletion
More informationC++ Templates. David Camp
C++ Templates David Camp C Marcos #define () #define min(i, j) (((i) < (j))? (i) : (j)) #define max(i, j) (((i) > (j))? (i) : (j)) #define RADTODEG(x)
More informationLecture No.04. Data Structures
Lecture No.04 Data Structures Josephus Problem #include "CList.cpp" void main(int argc, char *argv[]) { CList list; int i, N=10, M=3; for(i=1; i
More informationCS6202 - PROGRAMMING & DATA STRUCTURES I Unit IV Part - A 1. Define Stack. A stack is an ordered list in which all insertions and deletions are made at one end, called the top. It is an abstract data type
More informationUniversity of Illinois at Urbana-Champaign Department of Computer Science. First Examination
University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section
More informationData Structure. Recitation VII
Data Structure Recitation VII Recursion: Stack trace Queue Topic animation Trace Recursive factorial Executes factorial(4) Step 9: return 24 Step 8: return 6 factorial(4) Step 0: executes factorial(4)
More information1. Stack Implementation Using 1D Array
Lecture 5 Stacks 1 Lecture Content 1. Stack Implementation Using 1D Array 2. Stack Implementation Using Singly Linked List 3. Applications of Stack 3.1 Infix and Postfix Arithmetic Expressions 3.2 Evaluate
More informationData Structures and Algorithms
Data Structures and Algorithms Alice E. Fischer Lecture 6: Stacks 2018 Alice E. Fischer Data Structures L5, Stacks... 1/29 Lecture 6: Stacks 2018 1 / 29 Outline 1 Stacks C++ Template Class Functions 2
More informationList, Stack, and Queues
List, Stack, and Queues R. J. Renka Department of Computer Science & Engineering University of North Texas 02/24/2010 3.1 Abstract Data Type An Abstract Data Type (ADT) is a set of objects with a set of
More informationcsci 210: Data Structures Stacks and Queues
csci 210: Data Structures Stacks and Queues 1 Summary Topics Stacks and Queues as abstract data types ( ADT) Implementations arrays linked lists Analysis and comparison Applications: searching with stacks
More informationIT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science
IT 4043 Data Structures and Algorithms Budditha Hettige Department of Computer Science 1 Syllabus Introduction to DSA Abstract Data Types List Operation Using Arrays Stacks Queues Recursion Link List Sorting
More informationDATA STRUCTURES: OVERVIEW AND ITS APPLICATIONS
DATA STRUCTURES: OVERVIEW AND ITS APPLICATIONS By Deepika Ratnakar Abstract This paper tries to throw light in the types of data structures and their application in the field of Computer Science. Computer
More information-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.
Topic 15 Implementing and Using "stack n. The set of things a person has to do in the future. "I haven't done it yet because every time I pop my stack something new gets pushed." If you are interrupted
More informationStack and Queue. Stack:
Stack and Queue Stack: Abstract Data Type A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations
More information1 P age DS & OOPS / UNIT II
UNIT II Stacks: Definition operations - applications of stack. Queues: Definition - operations Priority queues - De que Applications of queue. Linked List: Singly Linked List, Doubly Linked List, Circular
More informationLecture 3: Stacks & Queues
Lecture 3: Stacks & Queues Prakash Gautam https://prakashgautam.com.np/dipit02/ info@prakashgautam.com.np 22 March, 2018 Objectives Definition: Stacks & Queues Operations of Stack & Queues Implementation
More informationQueue with Array Implementation
Queue with Array Implementation SCSJ2013 Data Structures & Algorithms Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi Faculty of Computing Objectives Queue concepts and applications. Queue structure and
More information