Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures and Algorithms IT12112 Lecture 03.

Similar presentations


Presentation on theme: "Data Structures and Algorithms IT12112 Lecture 03."— Presentation transcript:

1 Data Structures and Algorithms IT12112 Lecture 03

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

3 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. Stacks (Cont.)

4 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.

5 Example

6 The Stack ADT The Stack ADT stores arbitrary objects Main stack operations: –push(object) : inserts an element –object pop() : removes and returns the last inserted element Auxiliary stack operations: –object top() : returns the last inserted element without removing it –integer size() : returns the number of elements stored –boolean isEmpty() : indicates whether no elements are stored 6

7 Basic operations of a Stack New Push PopPeek ? Empty ?

8 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 Stack implemented in an array

9 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.

10 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.

11 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.

12 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

13 How the stack routines work: empty stack;push(a), push(b); pop Push (a)‏ top= 0 a Push (b)‏ b a Stack is empty top=-1 top= 1 pop top =0 a

14 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

15 Stack Algorithms Push(item) { If (stack is full) print “ stack over flow” else Increment top ; Stack [top]= item; } 15

16 Pop() { If( stack is empty) print” stack under flow” else Decrement top } 16

17 Display() { If ( stack is empty) print” no element to display” else for i= top to 0 step -1 Print satck[i]; } 17

18 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) 18 S 012 t … Algorithm pop(): if isEmpty() then throw EmptyStackException else e  S[t] S[t]  NULL t  t  1 return e

19 19 Algorithm IsEmpty(): return (t<0) Algorithm top(): if IsEmpty() then throw EmptyStackException else return S[t] Algorithm push(o): if Size()=N then throw FullStackException else t  t + 1 S[t]  o Algorithm Size(): return t+1

20 #include using namespace std; #define MAX 10 // MAXIMUM STACK CONTENT class stack { private: int arr[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 } Implementation

21 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; }

22 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";

23 cout<<a.pop()<<" is Popped\n"; return 0; } OUTPUT: 3 is Pushed 10 is Pushed 1 is Pushed 1 is Popped 10 is Popped 3 is Popped

24 Implementation #include class stack { int stk[5]; int top; public: stack() { top=-1; } 24

25 void push(int x) { if(top > 4) { cout <<"stack over flow"; return; } stk[++top]=x; cout <<"inserted" <<x; } 25

26 void pop() { if(top <0) { cout <<"stack under flow"; return; } cout <<"deleted" <<stk[top--]; } 26

27 27 void display() { if(top<0) { cout <<" stack empty"; return; } for(int i=top;i>=0;i--) cout <<stk[i] <<" "; } };

28 void main() { int ch; 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); } 28

29 OUTPUTS 29 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

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

31 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 item to 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? Queue

32 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.

33 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) ABCD front rear Inserted Removed

34 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

35 Basic operations of a queue New Enqueue Dequeue Empty? ? Full?

36 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

37 Basic array implementation of queues ABCD front rear insertion removal

38 Queue initialisation For an empty queue Front,rear For an empty queue rear must be initialised to rear-1, Front=-1,rear=-1 and size=0

39 Array implementation of queues E.g: Size=0,front=-1,rear=-1 Size=1,front=-1,rear=0 Enqueue(A) A

40 Size=2,front=-1,rear=1 A Enqueue(B) B Size=1,front=0,rear=1 Dequeue() B

41 Size=0,front=1,rear=1 Dequeue Size=7,front=1,rear=8 After 7 Enqueus CDEFGHI

42 Queue Algorithms Insert ( item) { If rear = max -1 then print “ queue is full” else { Increment rear Queue [rear]=item; }

43 Delete() { If front = rear print “queue is empty” else Increment front }

44 Display() { If front=rear print “queue is empty “ else For i =front to rear Print queue[i]; }

45 45 Algorithm IsEmpty(): return (f = r) Algorithm front(): if IsEmpty() then throw EmptyQueueException else return Q[f] Algorithm enqueue(o): if Size()=N -1 then throw FullQueueException else Q[r]  o r  (r + 1) mod N Algorithm Size(): return (N – f + r) mod N Algorithm dequeue(): if isEmpty() then throw EmptyQueueException else e  Q[f] Q[f]  NULL f  (f + 1) mod N return e

46

47 Queue Implementation #include class queue { int queue[5]; int rear,front; public: queue() {rear=-1; front=-1; }

48 void insert(int x) { if(rear > 4) { cout <<"queue over flow"; rear=-1; return; } queue[++rear]=x; cout <<"inserted" <<x; }

49 void delete() { if(front==rear) { cout <<"queue under flow"; return; } cout <<"deleted" <<queue[++front]; }

50 void display() { if(rear==front) { cout <<" queue empty"; return; } for(int i=front+1;i<=rear;i++) cout <<queue[i]<<" "; }

51 void main() { int ch; queue qu; clrscr(); while(1) { cout <<"\n1.insert 2.delet 3.display 4.exit\nEnter ur choice"; cin >> ch; switch(ch) { case 1: cout <<"enter the element"; cin >> ch; qu.insert(ch); break; case 2: qu.delet(); break; case 3: qu.display();break; case 4: exit(0); }

52 #include #define MAX 5 // MAXIMUM CONTENTS IN QUEUE class queue { private: int t[MAX]; int al; // Addition End int dl; // Deletion End public: queue() { dl=-1; al=-1; } Queue Implementation

53 void del() { int tmp; if(dl==-1) { cout<<"Queue is Empty"; } else { for(int j=0;j<=al;j++) { if((j+1)<=al) { tmp=t[j+1]; t[j]=tmp; }

54 else { al--; if(al==-1) dl=-1; else dl=0; }

55 void add(int item) { if(dl==-1 && al==-1) { dl++; al++; } else { al++; if(al==MAX) { cout<<"Queue is Full\n"; al--; return; } t[al]=item; }

56 void display() { if(dl!=-1) { for(int iter=0 ; iter<=al ; iter++) cout<<t[iter]<<" "; } else cout<<"EMPTY"; } };

57 int main() { queue a; int data[5]={32,23,45,99,24}; cout<<"Queue before adding Elements: "; a.display(); cout<<endl<<endl; for(int iter = 0 ; iter < 5 ; iter++) { a.add(data[iter]); cout<<"Addition Number : "<<(iter+1)<<" : "; a.display(); cout<<endl; }

58 cout<<endl; cout<<"Queue after adding Elements: "; a.display(); cout<<endl<<endl; for(iter=0 ; iter < 5 ; iter++) { a.del(); cout<<"Deletion Number : "<<(iter+1)<<" : "; a.display(); cout<<endl; } return 0; }

59 OUTPUT: Queue before adding Elements: EMPTY Addition Number : 1 : 32 Addition Number : 2 : 32 23 Addition Number : 3 : 32 23 45 Addition Number : 4 : 32 23 45 99 Addition Number : 5 : 32 23 45 99 24 Queue after adding Elements: 32 23 45 99 24 Deletion Number : 1 : 23 45 99 24 Deletion Number : 2 : 45 99 24 Deletion Number : 3 : 99 24 Deletion Number : 4 : 24 Deletion Number : 5 : EMPTY

60 There is plenty of extra space :All the positions before the front are unused and can thus be recycled. When either rear or front reaches the end of the array, we reset it to the beginning. This operation is called a circular array implementation.

61 Circular array implementation

62 Size=7,front=1,rear=8 After 7 Enqueus CDEFGHI Size=8,front=1,rear=0 Enqueus(J) CDEFGHIJ Circular array implementation (Array implementation of the queue with wraparound)

63 Queue Implementation 1: Circular Array Again we use an array of fixed size K But now we keep two indexes: tail and head headtail K

64 New Queue (Array) Head = 0 Tail = 0 headtail

65 Enqueue(x) (Array) Put x into array at tail, then move tail headtail X

66 Dequeue(x) (Array) Return element x at head Advance head headtail XYZW

67 Dequeue(x) (Array) Return element x at head Advance head headtail XYZW

68 Enqueue(x) -- Cont’d (Array) But what happens when tail is at end of array We can put X in, but then what? How do we advance tail? headtail YZ X

69 Enqueue(x) -- Cont’d (Array) tail is now moved to the beginning of the array tail  (tail + 1) modulo K –tail = (tail+1) % K headtail YZX

70 Dequeue(x) -- Cont’d (Array) And what happens when head reaches end? Same thing: head  (head + 1) modulo K headtail YZX

71 Dequeue(x) -- Cont’d (Array) And what happens when head reaches end? Same thing: head  (head + 1) modulo K headtail YZX

72 Empty? (Array) When head catches up with tail headtail

73 Empty? (Array) When head catches up with tail headtail

74 Empty? (Array) When head catches up with tail head == tail headtail

75 Queue Run-time complexity is appealing: enqueue(), dequeue(), … are all O(1) Storage complexity: O (N), where N is the size of the array, determined at the time queue is created.

76 An example of using queue One printer is connected to several computers In computer networks. there are many network setups of personal computers in which the disk is attached to one machine known as the file server. because service is first come first served. Printing a file takes much longer time than transmitting the data; a queue of printing jobs is needed When new job P arrives, do enqueue(P) When a job is finished, do dequeue(P)


Download ppt "Data Structures and Algorithms IT12112 Lecture 03."

Similar presentations


Ads by Google