760 likes | 775 Views
Learn about stacks, a commonly used data structure in coding, and their implementation using arrays and linked lists. Discover stack operations and their applications in processors and other programming scenarios.
E N D
www.hndit.com Data Structures and AlgorithmsIT12112 Lecture 03
Stacks www.hndit.com • Stacks are commonly used Data Structures while writing code. • Consider this situation. • There are a pile of 5 Books on a Table. You want to add one book to the pile. What do you do??? • You simply add the book on the TOP of the pile. • What if you want the third book from the new 6 book pile? • You then lift each book one by one from the TOP until the third book reaches the top. Then you take the third book and replace all the others back into the pile by adding them from the TOP.
www.hndit.com Stacks (Cont.) • Data is stored in a Stack where adding of data is permitted only from the top. Removing/Deleting Data is also done from the top. • Where Stacks are used?Stacks are in fact used on every Processor. Each processor has a stack where data and addresses are pushed or added to the stack. Again the TOP rule is followed here. • The ESP Register adds as a Stack Pointer that refers to the top of the stack in the Processor. • Adding Data to the Stack is known as Pushing and deleting data from the stack is known as Popping.
www.hndit.com Stacks (Cont.) • A stack is a linear data structure which can be accessed only at one of its ends for storing and retrieving data. • There are two ways of implementing a stack Array (Static) and linked list (dynamic). • A stack is a special kind of list in which all insertions and deletions take place at one end, called the top. Therefore, it has another name ``pushdown list''. • Its items are added and deleted on a last-in-first-out (LIFO) basis. • Items can be both pushed and popped using O(1) time. Therefore very quick.
Example www.hndit.com
www.hndit.com The Stack ADT • The Stack ADT stores arbitrary objects • Main stack operations: • push(object): inserts an element • objectpop(): removes and returns the last inserted element • Auxiliary stack operations: • objecttop(): returns the last inserted element without removing it • integersize(): returns the number of elements stored • booleanisEmpty(): indicates whether no elements are stored
www.hndit.com Basic operations of a Stack Push New ? Pop Peek ? Empty
www.hndit.com Stack implemented in an array • Note that all operations need check array bounds • Pushing onto a full stack: Overflow • When h=K • Popping an empty stack: Underflow • When h<0
www.hndit.com Static Application (Array Based ) • The array implementation of our collection has one serious drawback: you must know the maximum number of items in your collection when you create it. • This presents problems in programs in which this maximum number cannot be predicted accurately when the program starts up. • Fortunately, we can use a structure called a linked list to overcome this limitation.
www.hndit.com Dynamic application (Linked list based) • The linked list is a very flexible dynamic data structure: items may be added to it or deleted from it at will. • A programmer need not worry about how many items a program will have to accommodate.
www.hndit.com Array implementation of Stacks • A stack can be implemented with an array and an integer. The integer top (Top of stack) provides the array index of the top element of the stack. • Thus if top is –1, the stack is empty.
www.hndit.com • A stack is generally implemented with only two principle operations (apart from a constructor and destructor methods): Push :adds an item to a stack Pop :extracts the most recently pushed item from the stack • Other methods such as top: returns the item at the top without removing it isempty :determines whether the stack has anything in it
How the stack routines work: empty stack;push(a), push(b); pop www.hndit.com a top= 0 Push (a) Stack is empty top=-1 b top= 1 top =0 a a pop Push (b)
www.hndit.com Array implementation Public operations • void push(x) – Insert x • void pop() – Remove most recently inserted item • Boolean isempty() – Return true if empty, false otherwise • void makeempty() – Remove all items
www.hndit.com Stack Algorithms Push(item) { If (stack is full) print “ stack over flow” else Increment top ; Stack [top]= item; }
www.hndit.com Pop() { If( stack is empty) print” stack under flow” else Decrement top }
www.hndit.com Display() { If ( stack is empty) print” no element to display” else fori= top to 0 step -1 Print satck[i]; }
… S 0 1 2 t www.hndit.com Array-based Stack • A simple way of implementing the Stack ADT uses an array • We add elements from left to right • A variable t keeps track of the index of the top element (size is t+1) Algorithmpop(): ifisEmpty()then throw EmptyStackException else e S[t] S[t] NULL tt 1 returne
Algorithmpush(o): ifSize()=N then throw FullStackException else tt +1 S[t] o www.hndit.com Algorithmtop(): ifIsEmpty() then throw EmptyStackException else return S[t] AlgorithmIsEmpty(): return (t<0) AlgorithmSize(): return t+1
www.hndit.com Implementation #include <iostream> using namespace std; #define MAX 10 // MAXIMUM STACK CONTENT class stack { private: intarr[MAX]; // Contains all the Data int top; //Contains location of Topmost Data pushed onto Stack public: stack() //Constructor { top=-1; //Sets the Top Location to -1 indicating an empty stack }
www.hndit.com void push(int a) // Push i.e. Add Value Function { if(top<MAX) { top++; // increment to by 1 arr[top]=a; //If Stack is Vacant store Value in Array } else { cout<<"STACK FULL!!"<<endl; } } int pop() // Delete Item. Returns the deleted item { if(top==-1) { cout<<"STACK IS EMPTY!!!"<<endl; return NULL; }
www.hndit.com else { int data=arr[top]; //Set Topmost Value in data arr[top]=NULL; //Set Original Location to NULL top--; // Decrement top by 1 return data; // Return deleted item } } }; int main() { stack a; a.push(3); cout<<"3 is Pushed\n"; a.push(10); cout<<"10 is Pushed\n"; a.push(1); cout<<"1 is Pushed\n\n";
www.hndit.com cout<<a.pop()<<" is Popped\n"; cout<<a.pop()<<" is Popped\n"; cout<<a.pop()<<" is Popped\n"; return 0; } OUTPUT:3 is Pushed10 is Pushed1 is Pushed1 is Popped10 is Popped3 is Popped
www.hndit.com Implementation #include<iostream.h> #include<conio.h> #include<stdlib.h> class stack { intstk[5]; int top; public: stack() { top=-1; }
www.hndit.com void push(int x) { if(top > 4) { cout <<"stack over flow"; return; } stk[++top]=x; cout <<"inserted" <<x; }
www.hndit.com void pop() { if(top <0) { cout <<"stack under flow"; return; } cout <<"deleted" <<stk[top--]; }
www.hndit.com void display() { if(top<0) { cout<<" stack empty"; return; } for(inti=top;i>=0;i--) cout <<stk[i] <<" "; } };
www.hndit.com void main() { intch; stack st; clrscr(); while(1) { cout <<"\n1.push 2.pop 3.display 4.exit\n Enter your choice"; cin >> ch; switch(ch) { case 1: cout <<"enter the element"; cin >> ch; st.push(ch); break; case 2: st.pop(); break; case 3: st.display();break; case 4: exit(0); } } }
www.hndit.com OUTPUTS 1.push 2.pop 3.display 4.exit Enter your choice2 stack under flow 1.push 2.pop 3.display 4.exit Enter your choice1 enter the element2 Inserted2 1.push 2.pop 3.display 4.exit Enter your choice1 enter the element3 inserted3
www.hndit.com Applications of Stacks • Direct applications • Page-visited history in a Web browser • Undo sequence in a text editor • Chain of method calls in the Java Virtual Machine or C++ runtime environment • Indirect applications • Auxiliary data structure for algorithms • Component of other data structures
www.hndit.com Queue There's a huge crowd at your local grocery store. There are too many people trying to buy their respective items and the Shopkeeper doesn’t know from where to start. Everyone wants their job done quickly and the shopkeeper needs an efficient method to solve this problem. What does he do? He introduces a Queue System based on the First Come, First Serve System. The Last Person trying to buy an item stands behind the last person at the END of the queue. The Shopkeeper however is present at the FRONT end of the queue. He gives the itemto the person in FRONT of the queue and after the transaction is done, the person in FRONT of the Queue Leaves. Then the person second in queue becomes the First person in the Queue.Do you get the point here?
www.hndit.com Queue • A queue is another special kind of list, where items are inserted at one end (the rear) and deleted at the other end (the front). • A queue is also called a FIFO, since the items are deleted in the same order as they were added - on a first-in-first-out basis. • For a queue structure, we have two special names for insertion and deletion: ENQUEUE and DEQUEUE.
rear front Removed A B C D Inserted www.hndit.com Queue Definition • A queue is an ordered collection of items from which items may be deleted at one end ( called front of the queue) and into which items may be inserted at the other end (called the rear of the queue)
www.hndit.com Queue ADT • Queue stores data according to order of arrival • First In, First Out • Basic operations: • Empty?, Full? ,new, …. • Enqueue(x) // adds x to the back of the queue • Dequeue() // removes returns top of queue
www.hndit.com Basic operations of a queue New Enqueue ? Dequeue Empty? Full?
www.hndit.com Queue implementation. • The queue class has four data fields • A dynamically expanding array • The number of items currently in the queue • The array index of the front item • The array index of the rear item
www.hndit.com Basic array implementation of queues rear front A B C D removal insertion
Front,rear www.hndit.com Queue initialisation • For an empty queue For an empty queue rear must be initialised to rear-1, Front=-1,rear=-1 and size=0
www.hndit.com Array implementation of queues E.g: Size=0,front=-1,rear=-1 Enqueue(A) A Size=1,front=-1,rear=0
www.hndit.com Enqueue(B) A B Size=2,front=-1,rear=1 Dequeue() B Size=1,front=0,rear=1
www.hndit.com Dequeue Size=0,front=1,rear=1 After 7 Enqueus C D E F G H I Size=7,front=1,rear=8
www.hndit.com Queue Algorithms Insert ( item) { If rear = max -1 then print “ queue is full” else { Increment rear Queue [rear]=item; } }
www.hndit.com Delete() { If front = rear print “queue is empty” else Increment front }
www.hndit.com Display() { If front=rear print “queue is empty “ else For i =front to rear Print queue[i]; }
AlgorithmIsEmpty(): return (f = r) AlgorithmSize(): return (N – f + r) mod N www.hndit.com Algorithmfront(): ifIsEmpty() then throw EmptyQueueException else return Q[f] Algorithmenqueue(o): ifSize()=N -1 then throw FullQueueException else Q[r] o r (r +1) mod N Algorithmdequeue(): ifisEmpty()then throw EmptyQueueException else e Q[f] Q[f] NULL f (f +1) mod N returne
www.hndit.com Queue Implementation #include<iostream.h> #include<conio.h> #include<stdlib.h> class queue { int queue[5]; intrear,front; public: queue() {rear=-1; front=-1; }
www.hndit.com void insert(int x) { if(rear > 4) { cout <<"queue over flow"; rear=-1; return; } queue[++rear]=x; cout <<"inserted" <<x; }
www.hndit.com void delete() { if(front==rear) { cout <<"queue under flow"; return; } cout <<"deleted" <<queue[++front]; }
www.hndit.com void display() { if(rear==front) { cout <<" queue empty"; return; } for(inti=front+1;i<=rear;i++) cout <<queue[i]<<" "; } }