Posts Implement Queue using Linked List (geeksforgeeks - SDE Sheet)
Post
Cancel

Implement Queue using Linked List (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Implement a Queue using Linked List.

A Query Q is of 2 Types

(i) 1 x (a query of this type means pushing ‘x’ into the queue)
(ii) 2 (a query of this type means to pop an element from the queue and print the poped element)

geeksforgeeks

SOLUTION

Push using rear pointer and pop from front.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class MyQueue
{
    QueueNode front, rear;

    //Function to push an element into the queue.
    void push(int a)
    {

        if(front == null){
            front = new QueueNode(a);
            rear = front;
        }else{
            rear.next = new QueueNode(a);
            rear = rear.next;
        }

    }

    //Function to pop front element from the queue.
    int pop()
    {

        if(front == null)
            return -1;
        else if(front == rear){
            int current = front.data;
            front = null;
            rear = null;
            return current;
        }else{
            int current = front.data;
            front = front.next;
            return current;
        }

    }
}
This post is licensed under CC BY 4.0 by the author.