(69). 24.2 Linked List Implementation Of Queue - anishsingh90/Data_Structure_And_Algorithm_In_Cpp_github.io GitHub Wiki

#include <bits/stdc++.h> using namespace std;

class node{ public: int data; node* next;

	node(int val){
		data = val;
		next = NULL;
	}

};

class Myqueue{

node* front;
node* back;

public:
	queue(){
		front = NULL;
		back = NULL;
	}
	
	
	//push operation
	void push(int x){
		node* n = new node(x);
		
		if(front==NULL){
			back = n;
			front = n;
			return;
		}
		back->next = n;
		back = n;
	}
	
	
	
	//pop operation
	void pop(){
		if(front==NULL){
			cout << "Queue underflow" << endl;
			return;
		}
		node* todelete = front;
		front = front->next;
		
		delete todelete;
	}
	
	
	
	//peek operation
	int peek(){
			if(front==NULL){
			cout << "No element in queue" << endl;
			return -1;
		}
		
		return front->data;
	}
	
	
	//empty operation
	bool empty(){
			if(front==NULL){
			return true;
	}
	return false;
}

};

int main(){ Myqueue q; q.push(1); q.push(2); q.push(3); q.push(4);

cout << q.peek() << endl; //PRINT FRONT = 1
q.pop(); //delete 1

cout << q.peek() << endl; //PRINT FRONT = 2
q.pop(); //delete 2

cout << q.peek() << endl; //PRINT FRONT = 3
q.pop(); //delete 3

cout << q.peek() << endl; //PRINT FRONT = 4
q.pop(); //delete 4

cout << "Check empty or not: ";
cout << q.empty() << endl; //print (1=true) = queue is empty

return 0;

}

/* OUTPUT: 1 2 3 4 Check empty or not: 1 */