# Stack and Queue

Post on 17-Jan-2017

73 views

Embed Size (px)

TRANSCRIPT

Stack and Queue

Stack and Queue APURBO DATTA

Overviewwhat is stack ?Stack in Programming.Basic operations of stack(Pushing, popping etc.) Implementation of StacksQueue DefinitionBasic operations of queueEnqueuing, dequeuing etc.Implementation of queue

Stack OverviewStack Definitionwhat is stack ?Condition of stack.Stack in Programming.Basic operations of stack(Pushing, popping etc.) Implementation of Stacks

Stack DefinitionWe know that the Stack is LIFO Structure i,e Last in First Out. It is very useful data structure in C Programming. Stack can be implemented using the Linked List or Array.

Stack is LIFO Structure [ Last in First Out ]Stack is Ordered List of Elements of Same Type.Stack is Linear ListIn Stack all Operations such as Insertion and Deletion are permitted at only one end called TopCondition of stack

Stack in ProgrammingSimilar is the idea of stack in Programming

1. You can add an element onto the stack.

2. You can remove the top most element.

3. You can see the top most element.

Push: Equivalent to an insertPop: Deletes the most recently inserted elementTop: Examines the most recently inserted elementFundamental operations

Push and PopPushAdd an element to the top of the stackPopRemove the element at the top of the stack

empty stacktop

top

push an element

A

A

A

Bpush anotherpoptop

top

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

We will explore implementations based on array and linked list

Lets see how to use an array to implement a stack first

Array Implementation of StackJust like the array implementation of the List, we also need the array of items where we are going to store the elements of the StackAside from this, we also need an object that keeps track of where the last element is locatedFrom this point on, we are going to call it the toptop is simply an integer (very much like the head in the cursor implementation of the List)

Our Stack class should look very much like this:const MAX = 100;class Stack{private:int top, items[MAX];public:Stack();bool push(int);bool pop();int peek(); //int top();bool isEmpty();bool isFull();void display();};Array Implementation of Stack

The constructorStack::Stack(){top = -1;}The full checkbool Stack::isFull(){if(top+1==MAX)return true;return false;}The empty checkbool Stack::isEmpty(){if(top==-1)return true;return false;}Array Implementation of StackThe pushbool Stack::push(int x){if(isFull())return false;items[++top] = x;return true;}The popbool Stack::pop(){if(isEmpty())return false;top--;return true;}

1013161922

top = -1top = 0top =1 top =2 top =3 top =41013161922

top = 0top =1 top =2 top =3 top =4Array Implementation of Stack

Linked-list Implementation of StackThis implementation is the linked-list implementation of the list except for the following operationsGeneral insert and appendGeneral delete

44972317

head:tail:

9

Linked-list Implementation of Stack44

97

23

17

9

PUSHtop:top:

44972317

top:tmptmptmptmpdel9

Linked-list Implementation of Stackpop

Queue OverviewQueue DefinitionBasic operations of queueEnqueuing, dequeuing etc.Implementation of queueArrayLinked list

What is QueueThe Queue is like the List but with limited insertion and deletion.Insertion can be done only at the end or rearDeletion can only be done in the frontFIFO first-in-first-out data structureOperationsenqueuedequeue

Basic operations of queuePrimary queue operations: Enqueue and DequeueLike check-out lines in a store, a queue has a front and a rear. EnqueueInsert an element at the rear of the queueDequeueRemove an element from the front of the queue

Insert (Enqueue)Remove(Dequeue)rearfront

C ProgramAlgorithmEnqueue Operation

AlgorithmC ProgramDequeue Operation

Storing a queue in a static data structureThis implementation stores the queue in an array. The array indices at which the head and tail of the queue are currently stored must be maintained. The head of the queue is not necessarily at index 0. The array can be a circular array the queue wraps round if the last index of the array is reached. Example storing a queue in an array of length 5

Storing a queue in a dynamic data structureEach node in a dynamic data structure contains data AND a reference to the next node.A queue also needs a reference to the head node AND a reference to the tail node.The following diagram describes the storage of a queue called Queue. Each node consists of data (DataItem) and a reference (NextNode).

The first node is accessed using the name Queue.Head.Its data is accessed using Queue.Head.DataItemThe second node is accessed using Queue.Head.NextNodeThe last node is accessed using Queue.Tail

Adding a node (Add) in a dynamic data structure The new node is to be added at the tail of the queue. The reference Queue.Tail should point to the new node, and the NextNode reference of the node previously at the tail of the queue should point to the DataItem of the new node.

Removing a node (Remove) in a dynamic data structureThe value of Queue.Head.DataItem is returned. A temporary reference Temp is declared and set to point to head node in the queue (Temp = Queue.Head). Queue.Head is then set to point to the second node instead of the top node.The only reference to the original head node is now Temp and the memory used by this node can then be freed.

Implementation of QueueJust 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

Array Implementation of Queue

1013161922

size=5size=1size=2size=3size=41013162922

size=1size=2size=3size=4size=5

/*Queue - Linked List implementation*/

#include#include

struct Node {int data;struct Node* next;};// Two l variables to store address of front and rear nodes. struct Node* front = NULL;struct Node* rear = NULL;

// To Enqueue an integervoid Enqueue(int x) {struct Node* temp = (struct Node*)malloc(sizeof(struct Node));temp->data =x; temp->next = NULL;if(front == NULL && rear == NULL){front = rear = temp;return;}rear->next = temp;rear = temp;}queue using linked list in c// To Dequeue an integer.void Dequeue() {struct Node* temp = front;if(front == NULL) {printf("Queue is Empty\n");return;}if(front == rear) {front = rear = NULL;}else {front = front->next;}free(temp);}

int Front() {if(front == NULL) {printf("Queue is empty\n");return;}return front->data;}

void Print() {struct Node* temp = front;while(temp != NULL) {printf("%d ",temp->data);temp = temp->next;}printf("\n");}int main(){/* Drive code to test the implementation. */// Printing elements in Queue after each Enqueue or Dequeue Enqueue(2); Print(); Enqueue(4); Print();Enqueue(6); Print();Dequeue(); Print();Enqueue(8); Print();

Implement queue using linked list in c

Comparing queue implementations Memory requirementsArray-based implementation Assume a queue (size: 100) of strings (80 bytes each) Assume indices take 2 bytes Total memory: (80 bytes x 101 slots) + (2 bytes x 2 indexes) = 8084 bytes Linked-list-based implementationAssume pointers take 4 bytes Total memory per node: 80 bytes + 4 bytes = 84 bytes

Comparing queue implementations(cont.)

Comparing queue implementationsBig-O Comparison of Queue OperationsOperationArray ImplementationLinked ImplementationClass constructorO(1)O(1)MakeEmptyO(1)O(N)IsFullO(1)O(1)IsEmptyO(1)O(1)EnqueueO(1)O(1)DequeueO(1)O(1)DestructorO(1)O(N)

Recommended