Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Stack
- #include<bits/stdc++.h>
- using namespace std;
- #define MAX 1000
- class Stack
- {
- int top;
- public:
- int a[MAX];
- Stack() { top = -1; }
- bool push(int x);
- int pop();
- bool isEmpty();
- };
- bool Stack::push(int x)
- {
- if (top >= (MAX-1))
- {
- cout << "Stack Overflow";
- return false;
- }
- else
- {
- a[++top] = x;
- cout<<x <<" pushed into stack\n";
- return true;
- }
- }
- int Stack::pop()
- {
- if (top < 0)
- {
- cout << "Stack Underflow";
- return 0;
- }
- else
- {
- int x = a[top--];
- return x;
- }
- }
- bool Stack::isEmpty()
- {
- return (top < 0);
- }
- int main()
- {
- class Stack s;
- s.push(10);
- s.push(20);
- s.push(30);
- cout<< "-------------------\n";
- cout<<s.pop() << " Popped from stack\n";
- cout<<s.pop() << " Popped from stack\n";
- cout<<s.pop() << " Popped from stack\n";
- cout<<s.pop() << " Popped from stack\n";
- return 0;
- }
- QUEUE:
- #include <iostream>
- #define SIZE 5
- using namespace std;
- class Queue {
- int items[SIZE], front, rear;
- public:
- Queue(){
- front = -1;
- rear = -1;
- }
- bool isFull();
- bool isEmpty();
- void enQueue(int element);
- int deQueue();
- void display();
- };
- bool Queue::isFull(){
- if(front == 0 && rear == SIZE - 1){
- return true;
- }
- if(front == rear + 1) {
- return true;
- }
- return false;
- }
- bool Queue::isEmpty(){
- if(front == -1)
- return true;
- else
- return false;
- }
- void Queue::enQueue(int element){
- if(isFull()){
- cout << "\nQueue is full\n---------------" << endl;
- } else {
- if(front == -1) front = 0;
- rear = (rear + 1) % SIZE;
- items[rear] = element;
- cout << endl << "-------------\nInserted " << element << endl;
- }
- }
- int Queue::deQueue(){
- int element;
- if(isEmpty()){
- cout << "Queue is empty" << endl;
- return(-1);
- } else {
- element = items[front];
- if(front == rear){
- front = -1;
- rear = -1;
- } /* Q has only one element, so we reset the queue after deleting it. */
- else {
- front=(front+1) % SIZE;
- }
- return(element);
- }
- }
- void Queue::display(){
- int i;
- if(isEmpty()) {
- cout << endl << "Empty Queue" << endl;
- }
- else
- {
- cout << "\nFront -> " << front;
- cout << endl << "Items -> ";
- for(i=front; i!=rear;i=(i+1)%SIZE)
- cout << items[i] <<" ";
- cout << items[i];
- cout << endl << "Rear -> " << rear;
- }
- }
- int main()
- {
- Queue q;
- q.deQueue();
- q.enQueue(1);
- q.display();
- q.enQueue(2);
- q.display();
- q.enQueue(3);
- q.display();
- q.enQueue(4);
- q.display();
- q.enQueue(5);
- q.display();
- q.enQueue(6);
- q.display();
- int elem = q.deQueue();
- if( elem != -1)
- cout << endl << "Deleted Element is " << elem;
- q.display();
- q.enQueue(7);
- q.display();
- q.enQueue(8);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement