Chapter 3. Stack & Queue 1

Size: px
Start display at page:

Download "Chapter 3. Stack & Queue 1"

Transcription

1 Chapter 3 Stacks & Queues Templates in C++ The Stack ADT The Queue ADT SubTypeing & Inheritance in C++ A Mazing Problem Evaluation of Expressions Multiple Stacks & Queues March 30, 2015 Stack & Queue 1

2 Template used in Selection Sort 1. Template <class KeyType> 2. void sort(keytype *a, int n) 3. //sort the n KeyTypes a[0] to a[n-1] into nondecreasing order 4. { 5. for (int i=0;i<n;i++) 6. { 7. int j=i; 8. // find smallest KeyType in a[i] to a[n-1] 9. for (int k=i+1;k<n;k++) 10. if (a[k]<a[j]) { j = k; 11. //interchange 12. KeyType temp=a[i];a[i]=a[j]; a[j]=temp; // practical examples float farray[100]; int intarray[200];.. sort(farray, 100); sort(intarray, 200); March 30, 2015 Stack & Queue 2

3 Copy Constructor The Copy Constructor is a special constructor that takes as its argument a reference to an object of the same class and creates a new object that is a copy. Shallow Copy By default, the compiler provides a copy constructor that performs a member-by-member copy from the original object to the one being created. This is called a member wise or shallow copy. In many cases a shallow copy is not satisfactory. Here is a simple program with a bare bones version of the Employee class. March 30, 2015 Stack & Queue 3

4 Copy Constructor (example) #include <iostream> using namespace std; class Employee { public: Employee(char *name, int id); ~Employee(); char *getname(){ return _name; //other accessor methods private: int _id; char *_name; ; Employee::Employee(char *name, int id) { _id = id; _name = new char[strlen(name) + 1]; // allocates an character array object strcpy(_name, name); Employee::~Employee() { delete [ ] _name; int main() { Employee programmer("john",22); cout << programmer.getname() << endl; return 0; Comments: Employee name is now stored in a dynamically allocated character array. It is of "string length + 1" to allow for the null terminator used with C-style strings, '\0'. The strcpy function automatically adds the null terminator to the destination string. Also, notice that the destructor frees the memory used to hold the employee name. This is needed to avoid a memory leak, March 30, 2015 Stack & Queue 4

5 Copy Constructor (example) int main() { Employee programmer("john",22); cout << programmer.getname() << endl; //Lots of code... Employee manager = programmer; //Creates a new Employee "manager", //which is an exact copy of the //Employee "programmer". Let s key in the example and run it anything wrong? return 0; It contains a serious bug and may die with an exception when run. The problem is that the default member-wise copy constructor is being used to create the "manager" object. But the member-wise copy copies the address stored in the pointer _name in "programmer" to the pointer _name in "manager". When you run the above program, programmer's destructor gets called first. It works fine and frees the block in memory. When manager's destructor is called, an exception is thrown when the delete is attempted because that block of memory has already been released. March 30, 2015 Stack & Queue 5

6 Copy Constructor (example) class Employee { public: Employee(char *name, int id); Employee(Employee &rhs); ~Employee(); char *getname(){return _name; int getid() {return _id; //other accessor methods private: int _id; char *_name; ; Employee::Employee(char *name, int id) { _id = id; Employee::~Employee() { delete[] _name; Employee::Employee(Employee &rhs) { _id = rhs.getid(); _name = new char[strlen(rhs.getname()) + 1]; strcpy(_name, rhs._name); _name = new char[strlen(name) + 1]; //allocates an character array object strcpy(_name, name); March 30, 2015 Stack & Queue 6

7 Template The Template (or parameterized type) can be viewed as a variable that can be instantiated to any data type (fundamental or user-defined type) Template function in C++ makes it easier to reuse classes and functions. Copy Constructor Is a special constructor which is invoked when an object is initialized with another object Ex. Keytype temp=a[k] Example Can we use the sort template for the Rectangle class? Well, not directly. We ll need to use operator overloading to implement > for Rectangle class. March 30, 2015 Stack & Queue 7

8 Using Templates to Represent Container Classes Container class a class that represents a data structure that contains or stores a number of objects. Objects can be pushed/deleted from a container class Array Bag Multiple occurrences of the same element Do not care about the position of an element Do not care which element is removed March 30, 2015 Stack & Queue 8

9 Using Templates to Represent Container Classes (Cont.) class Bag { public: Bag(int MaxSize=DefaultSize); ~Bag(); void Push(int); //insert an integer into bag int Delete(int&);//delete an integer from bag Boolean IsFull; Boolean IsEmpty(); private: void Full(); //action when bag is full void Empty();//action when bag is empty int *array; int MaxSize; //size of array int top; //highest position in array that contains an element ; Bag can only be used to store integers. We would like to implement Bag using templates so that it can be used to store objects of any data type. See Prog. 3.5~3.6. March 30, 2015 Stack & Queue 9

10 Implement Container Class with Template 1.Prefix the class definition of Bag & the definitions of all its member function with the statement: template<class Type> 2. int is replaced by Type when it refers to an object being stored in Bag 3. In all member functions headers The instance of Bag that associates the function with class Bag is followed by <Type> March 30, 2015 Stack & Queue 10

11 template <class Type> Bag<Type>::Bag(int MaxBagSize):MaxSize(MaxBagSize) { array=new Type[MaxSize]; top=-1; template <class Type> Bag <Type>::~Bag(){ delete[]array; template <class Type> void Bag<Type>::Push(const Type&x){ if(isfull()) Full(); else array[++top]=x; template <class Type> Type* Bag<Type>::Delete(Type&x){ if(isempty()) {Empty(); return 0; int deletepos = top /2; x=array[deletepos]; for(int index=deletepos; index<top; index++) array[index]=array[index+1]; // compact upper half of array top--; return &x; Prog. 3.6 Use constant reference (&x): 1. Type may represent large object, considerable overhead may be incurred if it is passed by value 2. It s assumed that Type were not int & or int && March 30, 2015 Stack & Queue 11

12 A stack Stack is an ordered list in which insertions and deletions are made at one end called the top. It is also called a Last- In-First-Out (LIFO) list. Given a stack S = (a 0,, a n-1 ), a 0 is the bottom element, a n-1 is the top element, and a i is on top of element a i-1, 0 < i < n. a 3 a 3 a 2 a 2 a 1 a 1 a 0 a 0 Push (Push) Pop (Delete) March 30, 2015 Stack & Queue 12

13 Example: System Stack Previous frame pointer fp Return Pushress a1 Previous frame pointer Return Pushress fp main Local variables Previous frame pointer Return Pushress main Used by a program at run time to process function calls The previous frame pointer points to the stack frame of the invoking function The return Pushress contains the location of the statement to be executed after the function terminates When the invoked function terminates, its stack frame is removed and the invoking function continues its processing March 30, 2015 Stack & Queue 13

14 Stack operations A top B A top C B A top D C B A top E D C B A top D C B A top Push Push Push Push del March 30, 2015 Stack & Queue 14

15 ADT 3.1 Abstract Data Type Stack template <class KeyType> class Stack { // objects: A finite ordered list with zero or more elements public: Stack (int MaxStackSize = DefaultSize); // Create an empty stack whose maximum size is MaxStackSize Boolean IsFull(); // if number of elements in the stack is equal to the maximum size // of the stack, return TRUE(1) else return FALSE(0) void Push(const KeyType& item); // if IsFull(), then StackFull(); else insert item into the top of the stack. Boolean IsEmpty(); // if number of elements in the stack is 0, return TRUE(1) else return FALSE(0) ; KeyType* Delete(KeyType& ); // if IsEmpty(), then StackEmpty() and return 0; // else remove and return a pointer to the top element of the stack. March 30, 2015 Stack & Queue 15

16 Implementation of Stack by Array a n-1 a 2 a 1 a 0 a 0 a 1 a 2 a n-1 Array index n-1 March 30, 2015 Stack & Queue 16

17 Queue A queue is an ordered list in which all insertions take place at one end and all deletions take place at the opposite end. It is also known as First-In-First-Out (FIFO) lists. Manipulation Issue It s intuitive to use array for implementing a queue. However, queue manipulations (Push and/or delete) will require elements in the array to move. In the worse case, the complexity is of O(MaxSize). a 0 a 1 a 2 a n-1 front rear March 30, 2015 Stack & Queue 17

18 Shifting Elements in Queue front rear front rear front rear March 30, 2015 Stack & Queue 18

19 The Queue ADT Queue: an ordered list All insertions take place at one end All deletions take pace at the opposite end First-In-First-Out, FIFO Example Given a queue Q={a 0,a 1,,a n-1 a 0 is the front element, a n-1 is the rear element a i is behind a i-1 for 1 i n March 30, 2015 Stack & Queue 19

20 ADT 3.2 Abstract Data Type Queue template <class KeyType> class Queue { // objects: A finite ordered list with zero or more elements public: Queue(int MaxQueueSize = DefaultSize); // Create an empty queue whose maximum size is MaxQueueSize ; Boolean IsFull(); // if number of elements in the queue is equal to the maximum size of // the queue, return TRUE(1); otherwise, return FALSE(0) void Push(const KeyType& item); // if IsFull(), then QueueFull(); else insert item at rear of the queue Boolean IsEmpty(); // if number of elements in the queue is equal to 0, return TRUE(1) // else return FALSE(0) KeyType* Delete(KeyType&); // if IsEmpty(), then QueueEmpty() and return 0; // else remove the item at the front of the queue and return a pointer to it March 30, 2015 Stack & Queue 20

21 Class Queue & Its Operations template<keytype> class Queue{ public: private: int front; //front: index of the first element to be retrieved int rear; //rear:index of the last element KeyType *queue; // KeyType array int MaxSize; A A B A B C A B C D A B C D E B C D E f,r f r f r f r f r f r Push Push Push Push delete March 30, 2015 Stack & Queue 21

22 Member Function of Queue template <class KeyType> Queue <Keytype>::Queue(int MaxQueuesize):MaxSize(MaxQueueSize) { queue = new KeyType[MaxSize]; front = rear = -1; template<class KeyType> inline Boolean Queue <Keytype>::IsFull(); { if (rear == MaxSize-1) return TRUE; else return FALSE; Template<KeyType> inline Boolean Queue<KeyType>::IsEmpty() { if(front == rear) return TRUE; else return FALSE; March 30, 2015 Stack & Queue 22

23 Member Function of Queue template <class KeyType> Void Queue <Keytype> ::Push(const KeyType &x) // Push x to the queue { if(isfull()) QueueFull(); else queue[++rear]=x; template <class KeyType> KeyType *Queue <Keytype> ::Delete(KeyType &x) // remove front element from the queue { if(isempty()) QueueEmpty(); return(); x=queue[++front]; return x; March 30, 2015 Stack & Queue 23

24 In operating system Job Scheduling (Fig. 3.5) if priorities are not used, the jobs are processed in the order they enter the system front Rear Q[0] Q[1] Q[2] Q[3] Q[4] Comments -1-1 queue empty Initial -1 0 J1 Job1 joins Q -1 1 J1 J2 Job2 joins Q -1 2 J1 J2 J3 Job3 joins Q 0 2 J2 J3 Job1 leaves Q 0 3 J2 J3 J4 Job4 joins Q 1 3 J3 J4 Job2 leaves Q March 30, 2015 Stack & Queue 24

25 Worst Case Scenario Job Scheduling It takes n-1 steps to Push a new job front Rear Q[0] Q[1] Q[2]. Q[n-1] Comments -1 n-1 J1 J2 J3. Jn Initial 0 n-1 J2 J3. Jn Delete J1-1 n-1 J2 J3 J4. Jn+1 Push Jn+1 Jobs J2 through Jn are moved 0 n-1 J3 J4 Jn+1 Delete J2-1 n-1 J3 J4 j5 Jn+2 Push Jn+2 March 30, 2015 Stack & Queue 25

26 Circular Queues Queue size = n, Jobs: J1, J2, J3, J4 4 J J3 J2 J1 1 0 n-1 n-2 n-3 n J4 0 J3 n-1 J2 J1 n-2 n-3 n-4 front = 0; rear = 4 front = n-4; rear = 0 March 30, 2015 Stack & Queue 26

27 Circular Queues To solve the issue of moving elements in queue circular queue assigns next element to q[0] when rear == MaxSize 1. Pointer front will always point one position counterclockwise from the first element in the queue. Queue is empty when front == rear. But it is also true when queue is full. This will be a problem. March 30, 2015 Stack & Queue 27

28 Circular Queues To resolve the issue (when front == rear) on whether the queue is full or empty, one way is to use only MaxSize 1 elements in the queue at any time. Each time when Pushing an item to the queue, a newrear is calculated before Pushing the item. If newrear == front, then the queue is full. Another way to resolve the issue is using a flag to keep track of the last operation. The drawback of the method is it tends to slow down Push and Delete function. March 30, 2015 Stack & Queue 28

29 Push an Element to Circular Q 4 J J3 J2 J1 1 0 n-1 n-4 n-3 n J4 0 J2 J3 n-1 J1 n-2 n-4 n-3 front = 0; rear = 4 front = n-4; rear = 0 template <KeyType> void Queue <KeyType>::Push(const KeyType &x) { int new_rear=(rear+1)%maxsize; if (front == new_rear) QueueFull(); else queue[rear = new_rear]=x; March 30, 2015 Stack & Queue 29

30 Delete an Element from Circular Q 4 J J3 J2 J1 1 0 n-1 n-4 n-3 n J4 0 J2 J3 n-1 J1 n-2 n-4 n-3 front = 0; rear = 4 front = n-4; rear = 0 template <KeyType> KeyType *Queue <KeyType> ::Delete(const KeyType &x) // remove front element from queue { if (front == rear) { QueueEmpty(); return(0); front = (front+1)%maxsize; x=queue[front]; return (&x); March 30, 2015 Stack & Queue 30

31 DeQue Definition A Double-ended queue (Deque) is a linear list in which Pushitions and deletions may be made at either end Exercise Design a data representation that maps a deque into a one-dimensional array Write algorithms to Push and delete elements from either end of the queue March 30, 2015 Stack & Queue 31

32 SubType & Inheritance in C++ Inheritance Is used to express IS-A relationship between ADTs Derived class IS-A base classes C++ provides a mechanism called public inheritance Ex: class Stack::public Bag The inherited members have the same level of access in the derived class as in the base class IS-A relation If B inherits from A, then B IS-A A. (A is more general than B) VW Beetle IS-A Car; Eagle IS-A Bird Chair IS-A furniture, Lion IS-A Mammal Rectangle IS-A Polygon Stack IS-A Bag March 30, 2015 Stack & Queue 32

33 Inheritance A derived class inherits all the non-private (e.g., protected and public) members (data and functions) of the base class. Inherited members from public inheritance have the same level of access in the derived class as they did in the base class. The derived class can reuse the implementation of a function in the base class or implement its own function, with the exception of constructor and destructor. March 30, 2015 Stack & Queue 33

34 Bag and Stack (old) class Bag { public: Bag(int MaxSize=defaultSize); // constructor ~Bag(); // destructor virtual void Push(int); virtual int *Delete(int&) virtual Boolean IsFull(); virtual Boolean IsEmpty(); protected: virtual void Full(); virtual void Empty(); int *array; int MaxSize; int top; // data members ; class stack:public Bag { public: Stack(int MaxSize=DefaultSize); ~Stack(); int *Delete(int &); // delete the element from stack ; Constructor & destructor cannot be reused March 30, 2015 Stack & Queue 34

35 Example of Derived Class (old) Stack:: Stack (int MaxStackSize) : Bag(MaxStackSize) { // Constructor for Stack calls constructor for Bag Stack::~Stack() { // Destructor for Bag is automatically called when Stack is destroyed. // This ensures that array is deleted. int* Stack::Delete(int& x) { if (IsEmpty()) {Empty(); return 0; x = array[top--]; return &x; Example: Stack s(3); int x s.push(1); s.push(2); b.push(3); // Stack::Push is not defined, so use Bag::Push instead s.delete(x) // use Stack::Delete, which calls Bag::IsEmpty and Bag::Empty // because these have not been redefined in Stack March 30, 2015 Stack & Queue 35

36 Bag and Stack (new) class Bag { public: Bag(int bagcapacity=10); // constructor virtual ~Bag(); // destructor virtual int Size() const; virtual bool IsEmpty() const; virtual int Element() const; virtual void Push(cont int); virtual void Pop() protected: int *array; int capacity; int top; class stack:public Bag { public: Stack(int stackcapacity=10); ~Stack(); int Top() const; void Pop(); // delete the element from stack ; March 30, 2015 Stack & Queue 36

37 Example of Derived Class (new) Stack::Stack(int stackcapacity):bag(stackcapacity){ // Constructor for Stack calls constructor for Bag Stack::~Stack(){ // destructor for Bag is automatically called when Stack is destroyed. const: means that // this ensure that array is deleted the function can only access data and int Stack::Top() const int Stack::Pop() const cannot change data { { if( IsEmpty( )) throw Stack is empty. ; return array[top]; if( IsEmpty( )) throw Stack is empty. Cannot delete ; top--; Bag b(3); Stack s(3); // uses Bag constructor to create array of size 3 // uses Stack constructor to create array of size 3 b.push(1); b.push(2); b.push(3); // use Bag::Push s.push(1); s.push(2); s.push(3); // Stack::Push not defined, so use Bag::Push. b.pop(); // uses Bag::Pop, which calls Bag::IsEmpty s.pop(); // uses Stack::Pop, which calls Bag::IsEmtpy because IsEmpty // has not been redefined in Stack. March 30, 2015 Stack & Queue 37

38 The Mazing Problem entrance *Figure 3.11: An example maze (p.153) 1: blocked path 0: through path exit March 30, 2015 Stack & Queue 38

39 Allowable Moves NW N NE [i-1][j-1] [i-1][j] [i-1][j+1] W [i][j-1] X [i][j+1] E [i][j] [i+1][j-1] [i+1][j] [i+1][j+1] SW S SE March 30, 2015 Stack & Queue 39

40 The Maze Problem (Cont.) Stack is used in solving the maze problem for storing the coordinates and direction. Use of another m x p array to mark any position that has been visited before. March 30, 2015 Stack & Queue 40

41 Coordinates of the Next Move The coordinates of the following move is computed by the following data structure [i-1][j-1] NW N [i-1][j] [i-1][j+1] N E W [i][j-1] X [i][j] [i][j+1] E struct offsets { int x, y; ; enum directions { N, NE, E, SE, S, SW, W, NW ; offset move[8]; the SW of (i, j) will be (g, h) where g= i + move[sw].x; h= j + move[sw].y; q move[q].x move[q].y N -1 0 NE -1 1 E 0 1 SE 1 1 S 1 0 SW 1-1 W 0-1 NW -1-1 March 30, 2015 Stack & Queue 41 [i+1][j-1] SW [i+1][j] S [i+1][j+1] SE

42 First Pass at Finding a Path Through a Maze Initialize the stack to the maze entrance coordinates and direction east; while (stack is not empty) { (i, j, dir) = coordinates and direction deleted from top of stack; while (there are more moves from (i, j)) { (g, h) = coordinates of next move; if ((g = = m) && (h = = p)) success; if ((!maze [g][h]) // legal move && (!mark [g][h])) // haven t been here before { mark [g ][h] = 1; dir = next direction to try; add (i, j, dir) to top of stack; (i, j, dir) = (g, h, N) ; cout << "No path in maze." << endl; an item of the stack: struct items{ int x, y, dir; March 30, 2015 Stack & Queue 42

43 Example: A Maze Problem Row0 Row Row Row Row4 C0 C1 C2 C3 C4 Stack Current Position Next Legal Move Stack operation (1,1) (1,2,E) Push(1,1,E) (1,2) (1,3,E) Push(1,2,E) (1,3) No legal move Pop to backtrack (1,2) (2,1,SW) Push(1,2,SW) (2,1) (3,2,SE) Push(2,1,SE) (3,2) (3,3,E) success! Pop out the entire stack (2,1,SE) (1,2,SW) (1,1,E) Complete path: (3,3) (3,2,E) (2,1,SE) (1,2,SW) (1,1,E) March 30, 2015 Stack & Queue 43

44 March 30, 2015 Stack & Queue 44

45 Evaluation of Expressions X=A/B-C+D*E-A*C with A=4,B=2,C=2, D=E=3 Interpretation 1 * and / have higher priorities ((4/2)- 2) +(3*3) - (4*2) = =1 Interpretation 2 + and have higher priorities (4/(2-2+3))*(3-4)*2 = (4/3) * (-1) * 2= March 30, 2015 Stack & Queue 45

46 Priority of Operands in C++ Evaluation of operators of the same priority will proceed left to right e.g., A/B*C (A/B) *C Priority Operator 1 Unary minus,! 2 *,/,% 3 +,- 4 <,<=,>,>= 5 ==,!= 6 && 7 with above priorities, we know how X=A/B-C+D*E-A*C will be evaluated, i.e, X=(((A/B)-C)+(D*E))-(A*C) March 30, 2015 Stack & Queue 46

47 Postfix Notation Compiler Translates an expression into a sequence of machine codes It first re-writes the expression into a form called postfix notation Infix notation The operations come in-between operands Postfix notation The operators appear after its operands Example Infix: A/B-C+D*E-A*C Postfix: AB/C-DE*+AC*- March 30, 2015 Stack & Queue 47

48 Evaluation of Postfix Notation Scanning the notation from left to right Store temporary result in T i, i 1 Infix: A/B-C+D*E-A*C Original expression: AB/C-DE*+AC*- T 1 = A/B Operation Postfix T 1 C-DE*+AC*- T 2 = T 1 C T 2 DE*+AC*- T 3 = D*E T 2 T 3 +AC*- T 4 = T 2 + T 3 T 4 AC*- T 5 = A*C T 4 T 5 - T 6 = T 4 -T 5 T 6 March 30, 2015 Stack & Queue 48

49 The virtues of Postfix Notation Evaluation is easier than others on postfix notation The need for parenthesis is eliminated The priority of operations is no longer relevant Evaluation of each operator Pop correct number of operands from the stack Perform the operation Push the results onto the stack March 30, 2015 Stack & Queue 49

50 Evaluation Algorithm (for postfix expression) void Eval(Expression e) // Evaluate the postfix expression e It is assumed that the last token (a token // is either an operator, operand, or # ) in e is #. A function NextToken is // used to get the next token from e. The function uses the stack stack { Stack<Token>stack; // initialize stack for (Token x = NextToken(e); x!= # ; x=nexttoken(e)) if (x is an operand) stack.push(x) // add to stack else { // operator remove the correct number of operands for operator x from stack; perform the operation x and store the result (if any) onto the stack; // end of eval Program 3.18, Evaluating postfix expressions (p.150) March 30, 2015 Stack & Queue 50

51 Infix to Postfix Algorithm Fully parenthesize the expression Move all operators so that they replace their corresponding right parenthesis Delete all parentheses Example: A/B-C+D*E-A*C ((((A/B)-C)+(D*E))-(A*C)) AB/C-DE*+AC*- March 30, 2015 Stack & Queue 51

52 Example1: infix to postfix Translate A+B C to ABC + All operands go directly to the output When the input tokens are exhausted all operators in the stack will be popped out Next token Stack Output None Empty None A Empty A + + A B + AB + AB The operator has a higher priority than +, so it is placed on top of + C + ABC March 30, 2015 Stack & Queue 52

53 Example2: infix to postfix Translate A (B+C)/D to ABC+ D/ Next Token Stack Output None Empty None A Empty A A ( ( A B ( AB + (+ AB C (+ ABC At this point we want to unstack down to the corresponding ( & then delete ( and ) ) ABC+ / / ABC+ D / ABC+ D/ Done Empty ABC+ D/ March 30, 2015 Stack & Queue 53

54 Priority-Based Stack Operation Left Parenthesis Behaves as an operator with high priority when it is not in the stack in-coming priority, icp( ( )=0 Behaves as one with low priority when it is in the stack in-stack priority, isp( ( )=8 Only the matching right parenthesis can get a in-stack left parenthesis unstacked Summary Operators are taken out of the stack as long as their instack priority s is numerically less than or equal to the incoming priority of the new operator Assuming that the icp( # )=8 March 30, 2015 Stack & Queue 54

55 Converting infix to postfix void postfix(expression e) // output the postfix form of the infix expression e.nexttoken // and stack are as in function eval (Program 3.18). It is assumed that // the last token in e is #. Also, # is used at the bottom of the stack { stack<token>stack; // initialize stack token y; stack.add( # ); for (token x = NextToken(e); x!= # ; x = NextToken(e)) { if (x is an operand) cout << x; else if (x = = ) ) // unstack until ( for (y=*stack.delete(y); y!= ( ; y=*stack.delete(y)) cout << y; else{ //x is an operator for (y=*stack.delete(y); isp(y)<=icp(x); y=*stack.delete(y)) cout <<y; stack.add(y); // unstack the last y that was unstacked stack.add(x); // push the current x into stack // end of expression; empty the stack while(!stack.isempty()); cout << *stack.delete(y); // end of postfix Higher value lower priority March 30, 2015 Stack & Queue 55

56 Converting infix to postfix void Postfix(Expression e) // output the postfix form of the infix expression e.nexttoken // and stack are as in function eval (Program 3.18). It is assumed that // the last token in e is #. Also, # is used at the bottom of the stack { Stack<Token>stack; // initialize stack stack.push( # ); for (Token x = NextToken(e); x!= # ; x = NextToken(e)) if (x is an operand) cout << x; else if (x = = ) ) {// unstack until ( for (;stack.top( )!= ( ; stack.pop( )) cout << stack.top( ); stack.pop( ); // unstack ( else { // x is an operator for (; isp(stack.top( )) <= icp(x); stack.pop( )) cout << stack.top( ); stack.push(x); // end of expression; empty the stack for (;!stack.isempty( ); cout << stack.top( ), stack.pop( )); cout << endl; Higher value lower priority March 30, 2015 Stack & Queue 56

57 Two stacks Multiple Stacks & Queues m-4 m-3 m-2 m-1 m / n 1 Stack A Stack B More than two stacks (n) memory is divided into n equal segments boundary[stack_no], top[stack_no] 0 stack_no < MAX_STACKS March 30, 2015 Stack & Queue 57

58 Multiple Stacks Divide memory into segments for n stacks m / n 1 m / n m-1 stack0 Stack 1 Stack n-1 b[0] b[1] b[2] b[n] t[0] t[1] t[2] t[n] March 30, 2015 Stack & Queue 58

59 Operations of Multiple Stacks m / n 1 m / n m-1 stack0 Stack 1 Stack n-1 b[0] b[1] b[2] b[n] t[0] t[1] t[2] t[n] template <class type> void Push(const int i, const type &x) // Push x to the i-th stack { if(t[i]==b[i+1]) StackFull(i); else M[++t[i]]=x; template <class Type> type* Delete(const int I, const Type &x) //Delete top element in the i-th stack { if( t[i]==b[i]) { StackEmpty(i); return(); x=m[t[i]--]; return(&x) March 30, 2015 Stack & Queue 59

60 StackFull Function Find the least j, i < j < n, s.t. t[j] < b[j+1] (find free space from right portion) or, largest j, 0 j < i, s.t. t[j] < b[j+1] (find free space from left portion) b[0] t[0] b[1] t[1] b[i] t[i] t[i+1] t[j] b[j+1] b[n] b[i+1] b[i+2] meet b=boundary, t=top Find free space from right or left *Figure 3.15: Configuration when stack i meets stack i+1, but there is still free space elsewhere in M (p. 156) March 30, 2015 Stack & Queue 60

61 Appendix March 30, 2015 Stack & Queue 61

62 Virtual vs. non-virtual function Difference the non-virtual member functions are resolved at compile time static binding. The virtual member functions are resolved during runtime dynamic binding. March 30, 2015 Stack & Queue 62

63 Homeworks Write the postfix & prefix form of the following expressions: ( a) A B C ( b) A B C D () c A* B C ( d) ( A B) D E/( F A* D) C ( e) A& & B C!( E F) (assuming C++ precedence) ( f)!( A& &!(( B C) ( C D))) ( C E) March 30, 2015 Stack & Queue 63

CHAPTER 3 STACKS AND QUEUES. Iris Hui-Ru Jiang Fall 2008

CHAPTER 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 information

Stacks and Queues. Introduction to Data Structures Kyuseok Shim SoEECS, SNU.

Stacks and Queues. Introduction to Data Structures Kyuseok Shim SoEECS, SNU. Stacks and Queues Introduction to Data Structures Kyuseok Shim SoEECS, SNU. 1 3.1 Templates in C++ Make classes and functions more reusable Without using templates (example) program 1.6 : Selection sort

More information

Data Structure. Chapter 3 Stacks and Queues. Department of Communication Engineering National Central University Jhongli, Taiwan.

Data Structure. Chapter 3 Stacks and Queues. Department of Communication Engineering National Central University Jhongli, Taiwan. Data Structure Chapter 3 Stacks and Queues Instructor: Angela Chih-Wei Tang Department of Communication Engineering National Central University Jhongli, Taiwan 29 Spring Outline Stack Queue A Mazing Problem

More information

CHAPTER 3 STACKS AND QUEUES

CHAPTER 3 STACKS AND QUEUES CHAPTER 3 STACKS AND QUEUES All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed Fundamentals of Data Structures in C /2nd Edition, Silicon Press, 2008.

More information

Stacks. Ordered list with property: Insertions and deletions always occur at the same end. INSERT DELETE A3 A3 TOP TOP TOP

Stacks. Ordered list with property: Insertions and deletions always occur at the same end. INSERT DELETE A3 A3 TOP TOP TOP Stacks Ordered list with property: Insertions and deletions always occur at the same end. INSERT A3 A3 TOP DELETE A2 TOP A2 A2 TOP A1 A1 A1 A0 A0 A0 Stacks Implementation Implementation with arrays: Declare

More information

STACKS AND QUEUES CHAPTER 3

STACKS AND QUEUES CHAPTER 3 CHAPTER 3 STACKS AND QUEUES All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed Fundamentals of Data Structures in C, CHAPTER 3 1 Stack: a Last-In-First-Out

More information

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi

Data 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 information

Lecture Data Structure Stack

Lecture 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 information

Queue Definition. Ordered list with property:

Queue Definition. Ordered list with property: Queue Definition Ordered list with property: All insertions take place at one end (tail) All deletions take place at other end (head) Queue: Q = (a 0, a 1,, a n-1 ) a0 is the front element, a n-1 is the

More information

Chapter3 Stacks and Queues

Chapter3 Stacks and Queues Chapter Stacks and Queues Stacks Stacks Using Dynamic Arrays Queues Circular Queues Using Dynamic Arrays A Maze Problem Evaluation of Expressions Multiple Stacks and Queues C-C Tsai P. Stacks A stack is

More information

IV. 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. 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 information

More Group HW. #ifndef Stackh #define Stackh. #include <cstdlib> using namespace std;

More 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 information

Data Structure - Stack and Queue-

Data Structure - Stack and Queue- Data Structure - Stack and Queue- Hanyang University Jong-Il Park STACK Stack ADT List that insertions and deletions can be performed at the end of the list Operations Push(X, S): insert X in the list

More information

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms Introduction Problem Solving on Computer Data Structures (collection of data and relationships) Algorithms 1 Objective of Data Structures Two Goals: 1) Identify and develop useful high-level data types

More information

NCUE CSIE Wireless Communications and Networking Laboratory CHAPTER 3. Stacks And Queues

NCUE CSIE Wireless Communications and Networking Laboratory CHAPTER 3. Stacks And Queues CHAPTER 3 Stacks And Queues 1 Stack Stack: a Last-In-First-Out (LIFO/FILO) list Push Pop C A B C B A Top 2 An application of stack: stack frame of function call Old frame pointer fp Return address al Old

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

[CS302-Data Structures] Homework 2: Stacks

[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 information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:

! 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

STACKS AND QUEUES. Problem Solving with Computers-II

STACKS 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 information

ADTs: Stacks and Queues

ADTs: Stacks and Queues 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

More information

Stacks and Their Applications

Stacks and Their Applications Chapter 5 Stacks and Their Applications We have been discussing general list structures. In practice, we often work with some restricted cases, in which insertions and/or deletions occur only at one or

More information

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1 Data Structure using C++ Lecture 04 Reading Material Data Structures and algorithm analysis in C++ Chapter. 3 3.1, 3.2, 3.2.1 Summary Stack Operations on a stack Representing stacks Converting an expression

More information

Lecture No.04. Data Structures

Lecture 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 information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 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 information

Two abstract data types. performed on them) Stacks Last In First Out (LIFO) Queues First In First Out (FIFO)

Two abstract data types. performed on them) Stacks Last In First Out (LIFO) Queues First In First Out (FIFO) Two abstract data types o Can be implemented using arrays or linked lists o Restricted lists (only a small number of operations are performed on them) Stacks Last In First Out (LIFO) Queues First In First

More information

Linear Data Structure

Linear Data Structure Linear Data Structure Definition A data structure is said to be linear if its elements form a sequence or a linear list. Examples: Array Linked List Stacks Queues Operations on linear Data Structures Traversal

More information

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science Containers: Stack Jordi Cortadella and Jordi Petit Department of Computer Science The Stack ADT A stack is a list of objects in which insertions and deletions can only be performed at the top of the list.

More information

Data Structures (INE2011)

Data Structures (INE2011) Data Structures (INE2011) Electronics and Communication Engineering Hanyang University Haewoon Nam Lecture 4 1 Stacks Insertion and deletion are made at one end () Last input first output (LIFO) Inserting

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

Overview of C++: Part 1

Overview of C++: Part 1 C++: Part 1 d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA C++ Overview

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT Containers: Stack The Stack ADT A stack is a list of objects in which insertions and deletions can only be performed at the top of the list. Also known as LIFO Last In, First Out) push insert an element

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract

More information

September 10,

September 10, September 10, 2013 1 Bjarne Stroustrup, AT&T Bell Labs, early 80s cfront original C++ to C translator Difficult to debug Potentially inefficient Many native compilers exist today C++ is mostly upward compatible

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

infix expressions (review)

infix expressions (review) Outline infix, prefix, and postfix expressions queues queue interface queue applications queue implementation: array queue queue implementation: linked queue application of queues and stacks: data structure

More information

CS6202 - 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 information

Infix to Postfix Conversion

Infix to Postfix Conversion Infix to Postfix Conversion Infix to Postfix Conversion Stacks are widely used in the design and implementation of compilers. For example, they are used to convert arithmetic expressions from infix notation

More information

Data Structures using OOP C++ Lecture 9

Data 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 information

CMSC 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 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 information

CMSC 4023 Chapter 11

CMSC 4023 Chapter 11 11. Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language Examples Parameterized Abstract Data Types Encapsulation Constructs Naming Encapsulations

More information

DEEPIKA KAMBOJ UNIT 2. What is Stack?

DEEPIKA KAMBOJ UNIT 2. What is Stack? What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you

More information

Arrays and Linked Lists

Arrays and Linked Lists Arrays and Linked Lists Abstract Data Types Stacks Queues Priority Queues and Deques John Edgar 2 And Stacks Reverse Polish Notation (RPN) Also known as postfix notation A mathematical notation Where every

More information

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved Stacks Chapter 5 Copyright 2012 by Pearson Education, Inc. All rights reserved Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions A Problem Solved: Checking for Balanced

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

Outline. Introduction Stack Operations Stack Implementation Implementation of Push and Pop operations Applications. ADT for stacks

Outline. Introduction Stack Operations Stack Implementation Implementation of Push and Pop operations Applications. ADT for stacks Stack Chapter 4 Outline Introduction Stack Operations Stack Implementation Implementation of Push and Pop operations Applications Recursive Programming Evaluation of Expressions ADT for stacks Introduction

More information

The 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. 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 information

Discussion of project # 1 permutations

Discussion of project # 1 permutations Discussion of project # 1 permutations Algorithm and examples. The main function for generating permutations is buildp. We don t need a separate class for permutations since the permutations objects are

More information

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016

Stacks. 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 information

Stacks and their Applications

Stacks 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 information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

Introduction to Computer and Program Design 2. Lesson 6. Stacks. James C.C. Cheng Department of Computer Science National Chiao Tung University

Introduction to Computer and Program Design 2. Lesson 6. Stacks. James C.C. Cheng Department of Computer Science National Chiao Tung University Introduction to Computer and Program Design 2 Lesson 6 Stacks James C.C. Cheng Department of Computer Science National Chiao Tung University Introduction Stack A data collection, a grouping of data items

More information

Fall, 2015 Prof. Jungkeun Park

Fall, 2015 Prof. Jungkeun Park Data Structures t and Algorithms Stacks Application Infix to Postfix Conversion Fall, 2015 Prof. Jungkeun Park Copyright Notice: This material is modified version of the lecture slides by Prof. Rada Mihalcea

More information

List, Stack, and Queues

List, 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 information

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...

More information

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

STACKS. 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 information

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

double 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 information

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S Stacks Stacks & Queues A linear sequence, or list, is an ordered collection of elements: S = (s 1, s 2,..., s n ) Stacks and queues are finite linear sequences. A Stack is a LIFO (Last In First Out) list.

More information

BBM 201 DATA STRUCTURES

BBM 201 DATA STRUCTURES BBM 201 DATA STRUCTURES Lecture 6: EVALUATION of EXPRESSIONS 2018-2019 Fall Evaluation of Expressions Compilers use stacks for the arithmetic and logical expressions. Example: x=a/b-c+d*e-a*c If a=4, b=c=2,

More information

BBM 201 DATA STRUCTURES

BBM 201 DATA STRUCTURES BBM 201 DATA STRUCTURES Lecture 6: EVALUATION of EXPRESSIONS 2017 Fall Evaluation of Expressions Compilers use stacks for the arithmetic and logical expressions. Example: x=a/b-c+d*e-a*c If a=4, b=c=2,

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

Abstract Data Types 1

Abstract 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 information

C++ Templates. David Camp

C++ 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 information

Introduction to the C programming language

Introduction 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 information

CS 216 Exam 1 Fall SOLUTION

CS 216 Exam 1 Fall SOLUTION CS 216 Exam 1 Fall 2004 - SOLUTION Name: Lab Section: Email Address: Student ID # This exam is closed note, closed book. You will have an hour and fifty minutes total to complete the exam. You may NOT

More information

Ch. 18: ADTs: Stacks and Queues. Abstract Data Type

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

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305 Q.1 If h is any hashing function and is used to hash n keys in to a table of size m, where n

More information

CMSC 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 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 information

Introduction to the C programming language

Introduction 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 information

Programming Abstractions

Programming 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 information

Networked Embedded System Patterns for C Developers. Overview of C (& C++) Programming Styles. Douglas C. Schmidt

Networked Embedded System Patterns for C Developers. Overview of C (& C++) Programming Styles. Douglas C. Schmidt Networked Embedded System Patterns for C Developers Part II: Professor Department of EECS d.schmidt@vanderbilt.edu Vanderbilt University www.dre.vanderbilt.edu/ schmidt/ (615) 343-8197 June 3, 2009 Motivation

More information

Abstract 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 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 information

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO) Outline stacks stack ADT method signatures array stack implementation linked stack implementation stack applications infix, prefix, and postfix expressions 1 Stacks stacks of dishes or trays in a cafeteria

More information

EEE2020 Data Structures and Algorithms Abstract Data Types: Stacks and Queues

EEE2020 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 information

Stacks. Revised based on textbook author s notes.

Stacks. Revised based on textbook author s notes. Stacks Revised based on textbook author s notes. Stacks A restricted access container that stores a linear collection. Very common for solving problems in computer science. Provides a last-in first-out

More information

Stacks, Queues (cont d)

Stacks, 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 information

// The next 4 functions return true on success, false on failure

// 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 information

! A data type for which: ! An ADT may be implemented using various. ! Examples:

! 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 information

Content: Learning Objectives

Content: Learning Objectives 1 BLOOM PUBLIC CHOOL Vasant Kunj, New Delhi Lesson Plan Class: XII ubject: Computer cience Month : July No of s: 21 Chapter:Data structure: Linked List TTT: 8 WT: 12 Content: Learning Objectives At the

More information

CS24 Week 4 Lecture 2

CS24 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 information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

EC8393FUNDAMENTALS 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 information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main

More information

Today s lecture. CS 314 fall 01 C++ 1, page 1

Today s lecture. CS 314 fall 01 C++ 1, page 1 Today s lecture Midterm Thursday, October 25, 6:10-7:30pm general information, conflicts Object oriented programming Abstract data types (ADT) Object oriented design C++ classes CS 314 fall 01 C++ 1, page

More information

CS 106B Lecture 5: Stacks and Queues

CS 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 information

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.

-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 information

CS250 Final Review Questions

CS250 Final Review Questions CS250 Final Review Questions The following is a list of review questions that you can use to study for the final. I would first make sure that you review all previous exams and make sure you fully understand

More information

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

CSC 222: Computer Programming II. Spring 2004

CSC 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 information

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University 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 information

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Discussion 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 information

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Cpt S 122 Data Structures. Course Review Midterm Exam # 1 Cpt S 122 Data Structures Course Review Midterm Exam # 1 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 1 When: Friday (09/28) 12:10-1pm Where:

More information

March 13/2003 Jayakanth Srinivasan,

March 13/2003 Jayakanth Srinivasan, Statement Effort MergeSort(A, lower_bound, upper_bound) begin T(n) if (lower_bound < upper_bound) Θ(1) mid = (lower_bound + upper_bound)/ 2 Θ(1) MergeSort(A, lower_bound, mid) T(n/2) MergeSort(A, mid+1,

More information

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

ADVANCED 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 information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

CSE143 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. 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 information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University 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 information