stack queue

50
Stacks and Queues

Upload: hoang-nguyen

Post on 12-Apr-2017

343 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: Stack queue

Stacks and Queues

Page 2: Stack queue

2

struct Node{ double data;Node* next;

};

class List {public:List(); // constructorList(const List& list); // copy constructor~List(); // destructorList& operator=(const List& list); // assignment operator

bool empty() const; // boolean functionvoid addHead(double x); // add to the headdouble deleteHead(); // delete the head and get the head element// List& rest(); // get the rest of the list with the head removed// double headElement() const; // get the head element

void addEnd(double x); // add to the enddouble deleteEnd(); // delete the end and get the end element// double endElement(); // get the element at the end

bool searchNode(double x); // search for a given xvoid insertNode(double x); // insert x in a sorted listvoid deleteNode(double x); // delete x in a sorted list

void print() const; // outputint length() const; // count the number of elements

private:Node* head;

};

More complete list ADT

Page 3: Stack queue

3

Stack Overview

Stack ADT Basic operations of stack

Pushing, popping etc. Implementations of stacks using

array linked list

Page 4: Stack queue

4

Stack A stack is a list in which insertion and deletion take

place at the same end This end is called top The other end is called bottom

Stacks are known as LIFO (Last In, First Out) lists. The last element inserted will be the first to be retrieved

Page 5: Stack queue

5

Push and Pop Primary operations: Push and Pop Push

Add an element to the top of the stack Pop

Remove the element at the top of the stack

top

empty stack

Atop

push an element

top

push another

A

Btop

pop

A

Page 6: Stack queue

6

Implementation of Stacks

Any list implementation could be used to implement a stack Arrays (static: the size of stack is given initially) Linked lists (dynamic: never become full)

We will explore implementations based on array and linked list

Page 7: Stack queue

7

class Stack {public:

Stack(); // constructorStack(const Stack& stack); // copy constructor~Stack(); // destructor

bool empty() const; void push(const double x); double pop(); // change the stack

double top() const; // keep the stack unchanged

// bool full(); // optional// void print() const;

private:…

};

Stack ADT

update,‘logical’ constructor/destructor, composition/decomposition

‘physical’ constructor/destructor

Compare with List, see that it’s ‘operations’ that define the type!

inspection, access

Page 8: Stack queue

8

Using Stackint main(void) {

Stack stack;stack.push(5.0);stack.push(6.5);stack.push(-3.0);stack.push(-8.0);stack.print();cout << "Top: " << stack.top() << endl;

stack.pop();cout << "Top: " << stack.top() << endl;while (!stack.empty()) stack.pop();stack.print();return 0;

}

result

Page 9: Stack queue

9

struct Node{ public:

double data;Node* next;

};

class Stack {public:

Stack(); // constructorStack(const Stack& stack); // copy constructor~Stack(); // destructor

bool empty() const; void push(const double x); double pop(); // change the stack

bool full(); // unnecessary for linked listsdouble top() const; // keep the stack unchanged

void print() const;

private:Node* top;

};

Stack using linked lists

Page 10: Stack queue

10

void List::addHead(int newdata){

Nodeptr newPtr = new Node;newPtr->data = newdata;newPtr->next = head;head = newPtr;

}

void Stack::push(double x){

Node* newPtr = new Node;newPtr->data = x;newPtr->next = top;top = newPtr;

}

From ‘addHead’ to ‘push’

Push (addHead), Pop (deleteHead)

Page 11: Stack queue

11

Implementation based on ‘existing’ linked lists

Optional to learn Good to see that we may ‘re-use’ linked lists

Page 12: Stack queue

12

Now let’s implement a stack based on a linked list To make the best out of the code of List, we implement Stack

by inheriting List To let Stack access private member head, we make Stack

as a friend of List

class List {public:

List() { head = NULL; } // constructor~List(); // destructor

bool empty() { return head == NULL; }Node* insertNode(int index, double x);int deleteNode(double x);

int searchNode(double x);void printList(void);

private:Node* head;friend class Stack;

};

Page 13: Stack queue

13

class Stack : public List {public:

Stack() {}~Stack() {}double top() {

if (head == NULL) {cout << "Error: the stack is empty." << endl;return -1;

}else

return head->data;}void push(const double x) { InsertNode(0, x); }double pop() {

if (head == NULL) {cout << "Error: the stack is empty." << endl;return -1;

}else {

double val = head->data;DeleteNode(val);return val;

}}

void printStack() { printList(); }};

Note: the stack implementation based on a linked list will never be full.

from List

Page 14: Stack queue

14

Stack using arrays

class Stack {public:

Stack(int size = 10); // constructor~Stack() { delete [] values; } // destructor

bool empty() { return top == -1; }void push(const double x);double pop();

bool full() { return top == maxTop; }double top();void print();

private:int maxTop; // max stack size = size - 1int top; // current top of stackdouble* values; // element array

};

Page 15: Stack queue

15

Attributes of Stack maxTop: the max size of stack top: the index of the top element of stack values: point to an array which stores elements of stack

Operations of Stack empty: return true if stack is empty, return false otherwise full: return true if stack is full, return false otherwise top: return the element at the top of stack push: add an element to the top of stack pop: delete the element at the top of stack print: print all the data in the stack

Page 16: Stack queue

16

Allocate a stack array of size. By default, size = 10.

Initially top is set to -1. It means the stack is empty. When the stack is full, top will have its maximum value, i.e.

size – 1.

Stack::Stack(int size /*= 10*/) {values = new double[size];top = -1;

maxTop = size - 1;}

Although the constructor dynamically allocates the stack array, the stack is still static. The size is fixed after the initialization.

Stack constructor

Page 17: Stack queue

17

void push(const double x); Push an element onto the stack Note top always represents the index of the top

element. After pushing an element, increment top.

void Stack::push(const double x) {if (full()) // if stack is full, print error

cout << "Error: the stack is full." << endl;else

values[++top] = x;}

Page 18: Stack queue

18

double pop() Pop and return the element at the top of the stack Don’t forgot to decrement top

double Stack::pop() {if (empty()) { //if stack is empty, print error

cout << "Error: the stack is empty." << endl;return -1;

}else {

return values[top--];}

}

Page 19: Stack queue

19

double top() Return the top element of the stack Unlike pop, this function does not remove the top

element

double Stack::top() {if (empty()) {

cout << "Error: the stack is empty." << endl;return -1;

}else

return values[top];}

Page 20: Stack queue

20

void print() Print all the elements

void Stack::print() {cout << "top -->";for (int i = top; i >= 0; i--)

cout << "\t|\t" << values[i] << "\t|" << endl;cout << "\t|---------------|" << endl;

}

Page 21: Stack queue

21

Stack Application: Balancing Symbols

To check that every right brace, bracket, and parentheses must correspond to its left counterpart e.g. [( )] is legal, but [( ] ) is illegal

Algorithm(1)   Make an empty stack.(2)   Read characters until end of file

i.    If the character is an opening symbol, push it onto the stackii.   If it is a closing symbol, then if the stack is empty, report an erroriii.  Otherwise, pop the stack. If the symbol popped is not the corresponding opening symbol, then report an error

(3)   At end of file, if the stack is not empty, report an error

Page 22: Stack queue

22

Stack Application: function calls and recursion

Take the example of factorial! And run it.

#include <iostream>using namespace std;

int fac(int n){int product;if(n <= 1) product = 1;else product = n * fac(n-1);return product;

}

void main(){int number;cout << "Enter a positive integer : " << endl;;cin >> number;cout << fac(number) << endl;

}

Page 23: Stack queue

23

Assume the number typed is 3. fac(3): has the final returned value 6

3<=1 ? No.product3 = 3*fac(2) product3=3*2=6, return 6,fac(2):

2<=1 ? No.product2 = 2*fac(1) product2=2*1=2, return 2, fac(1):

1<=1 ? Yes.return 1

Tracing the program …

Page 24: Stack queue

24

fac(3) prod3=3*fac(2)

prod2=2*fac(1)fac(2)

fac(1) prod1=1

Call is to ‘push’ and return is to ‘pop’!

top

Page 25: Stack queue

25

Array versus linked list implementations

push, pop, top are all constant-time operations in both array and linked list implementation For array implementation, the operations are

performed in very fast constant time

Page 26: Stack queue

26

Queue Overview

Queue ADT Basic operations of queue

Enqueuing, dequeuing etc. Implementation of queue

Linked list Array

Page 27: Stack queue

27

Queue

A queue is also a list. However, insertion is done at one end, while deletion is performed at the other end.

It is “First In, First Out (FIFO)” order. Like customers standing in a check-out line in a

store, the first customer in is the first customer served.

Page 28: Stack queue

28

Enqueue and Dequeue Primary queue operations: Enqueue and Dequeue Like check-out lines in a store, a queue has a front

and a rear. Enqueue – insert an element at the rear of the

queue Dequeue – remove an element from the front of

the queue

Insert (Enqueue)

Remove(Dequeue) rearfront

Page 29: Stack queue

29

Implementation of Queue

Just as stacks can be implemented as arrays or linked lists, so with queues.

Dynamic queues have the same advantages over static queues as dynamic stacks have over static stacks

Page 30: Stack queue

30

class Queue {public:

Queue();Queue(Queue& queue);~Queue();

bool empty();void enqueue(double x);double dequeue();

void print(void);// bool full(); // optional

private:…

};

Queue ADT

‘physical’ constructor/destructor

‘logical’ constructor/destructor

Page 31: Stack queue

31

Using Queueint main(void) {

Queue queue;cout << "Enqueue 5 items." << endl;for (int x = 0; x < 5; x++)

queue.enqueue(x);cout << "Now attempting to enqueue again..." << endl;queue.enqueue(5);queue.print();double value;value=queue.dequeue();cout << "Retrieved element = " << value << endl;queue.print();queue.enqueue(7);queue.print();return 0;

}

Page 32: Stack queue

32

Struct Node {double data;Node* next;

}

class Queue {public:

Queue();Queue(Queue& queue);~Queue();

bool empty();void enqueue(double x);double dequeue();

// bool full(); // optionalvoid print(void);

private:Node* front; // pointer to front nodeNode* rear; // pointer to last nodeint counter; // number of elements

};

Queue using linked lists

Page 33: Stack queue

33

class Queue {public:

Queue() { // constructorfront = rear = NULL;counter = 0;

}~Queue() { // destructor

double value;while (!empty()) dequeue(value);

}bool empty() {

if (counter) return false;else return true;

}void enqueue(double x);double dequeue();

// bool full() {return false;};void print(void);

private:Node* front; // pointer to front nodeNode* rear; // pointer to last nodeint counter; // number of elements, not compulsary

};

Implementation of some online member functions …

Page 34: Stack queue

34

Enqueue (addEnd)void Queue::enqueue(double x) {

Node* newNode = new Node;newNode->data = x;newNode->next = NULL;

if (empty()) {front = newNode;

}else {

rear->next = newNode;}

rear = newNode;counter++;

}

8rear

rear

newNode

5

58

Page 35: Stack queue

35

Dequeue (deleteHead)double Queue::dequeue() {

double x;if (empty()) {

cout << "Error: the queue is empty." << endl;exit(1); // return false;

}else {

x = front->data;Node* nextNode = front->next;delete front;front = nextNode;counter--;

}return x;

}

front

583

8 5front

Page 36: Stack queue

36

Printing all the elements

void Queue::print() {cout << "front -->";Node* currNode = front;for (int i = 0; i < counter; i++) {

if (i == 0) cout << "\t";else cout << "\t\t"; cout << currNode->data;if (i != counter - 1)

cout << endl;else

cout << "\t<-- rear" << endl;currNode = currNode->next;

}}

Page 37: Stack queue

37

Queue using Arrays There are several different algorithms to

implement Enqueue and Dequeue Naïve way

When enqueuing, the front index is always fixed and the rear index moves forward in the array.

front

rear

Enqueue(3)

3

front

rear

Enqueue(6)

3 6

front

rear

Enqueue(9)

3 6 9

Page 38: Stack queue

38

Naïve way (cont’d) When dequeuing, the front index is fixed, and the

element at the front the queue is removed. Move all the elements after it by one position. (Inefficient!!!)

Dequeue()front

rear

6 9

Dequeue() Dequeue()

front

rear

9

rear = -1

front

Page 39: Stack queue

39

A better way When enqueued, the rear index moves forward. When dequeued, the front index also moves forward

by one element

XXXXOOOOO (rear) OXXXXOOOO (after 1 dequeue, and 1 enqueue)OOXXXXXOO (after another dequeue, and 2 enqueues)OOOOXXXXX (after 2 more dequeues, and 2 enqueues)

(front)

The problem here is that the rear index cannot move beyond the last element in the array.

Page 40: Stack queue

40

Using Circular Arrays Using a circular array When an element moves past the end of a circular

array, it wraps around to the beginning, e.g. OOOOO7963 4OOOO7963 (after Enqueue(4))

How to detect an empty or full queue, using a circular array algorithm? Use a counter of the number of elements in the queue.

Page 41: Stack queue

41

class Queue {public:

Queue(int size = 10); // constructorQueue(Queue& queue); // not necessary!

~Queue() { delete [] values; } // destructor

bool empty(void);void enqueue(double x); // or bool enqueue();double dequeue();

bool full();void print(void);

private:int front; // front indexint rear; // rear indexint counter; // number of elementsint maxSize; // size of array queuedouble* values; // element array

};

full() is not essential, can be embedded

Page 42: Stack queue

42

Attributes of Queue front/rear: front/rear index counter: number of elements in the queue maxSize: capacity of the queue values: point to an array which stores elements of the queue

Operations of Queue empty: return true if queue is empty, return false otherwise full: return true if queue is full, return false otherwise enqueue: add an element to the rear of queue dequeue: delete the element at the front of queue print: print all the data

Page 43: Stack queue

43

Queue constructor Queue(int size = 10)

Allocate a queue array of size. By default, size = 10. front is set to 0, pointing to the first element of the

array rear is set to -1. The queue is empty initially.

Queue::Queue(int size /* = 10 */) {values = new double[size];maxSize = size;front = 0;rear = -1;counter = 0;

}

Page 44: Stack queue

44

Empty & Full Since we keep track of the number of elements

that are actually in the queue: counter, it is easy to check if the queue is empty or full.

bool Queue::empty() {if (counter==0) return true;else return false;

}bool Queue::full() {

if (counter < maxSize) return false;else return true;

}

Page 45: Stack queue

45

Enqueue

void Queue::enqueue(double x) {if (full()) {

cout << "Error: the queue is full." << endl;exit(1); // return false;

}else {

// calculate the new rear position (circular)rear = (rear + 1) % maxSize; // insert new itemvalues[rear] = x;// update countercounter++;// return true;

}}

Or ‘bool’ if you want

Page 46: Stack queue

46

Dequeue

double Queue::dequeue() {double x;if (empty()) {

cout << "Error: the queue is empty." << endl;exit(1); // return false;

}else {

// retrieve the front itemx = values[front];// move front front = (front + 1) % maxSize;// update countercounter--;// return true;

}return x;

}

Page 47: Stack queue

47

Printing the elements

void Queue::print() {cout << "front -->";for (int i = 0; i < counter; i++) {

if (i == 0) cout << "\t";else cout << "\t\t"; cout << values[(front + i) % maxSize];if (i != counter - 1)

cout << endl;else

cout << "\t<-- rear" << endl;}

}

Page 48: Stack queue

48

Using Queueint main(void) {

Queue queue;cout << "Enqueue 5 items." << endl;for (int x = 0; x < 5; x++)

queue.enqueue(x);cout << "Now attempting to enqueue again..." << endl;queue.enqueue(5);queue.print();double value;value=queue.dequeue();cout << "Retrieved element = " << value << endl;queue.print();queue.enqueue(7);queue.print();return 0;

}

Page 49: Stack queue

49

Results

Queue implemented using linked list will be never full!

based on array based on linked list

Page 50: Stack queue

50

Queue applications

When jobs are sent to a printer, in order of arrival, a queue.

Customers at ticket counters …