-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathQueueThroughLinkedList_C#
84 lines (71 loc) · 1.66 KB
/
QueueThroughLinkedList_C#
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// C# program for linked-list
// implementation of queue
using System;
// A linked list (LL) node to
// store a queue entry
class QNode {
public int key;
public QNode next;
// constructor to create
// a new linked list node
public QNode(int key)
{
this.key = key;
this.next = null;
}
}
// A class to represent a queue The queue,
// front stores the front node of LL and
// rear stores the last node of LL
class Queue {
public QNode front, rear;
public Queue() { this.front = this.rear = null; }
// Method to add an key to the queue.
public void enqueue(int key)
{
// Create a new LL node
QNode temp = new QNode(key);
// If queue is empty, then new
// node is front and rear both
if (this.rear == null) {
this.front = this.rear = temp;
return;
}
// Add the new node at the
// end of queue and change rear
this.rear.next = temp;
this.rear = temp;
}
// Method to remove an key from queue.
public void dequeue()
{
// If queue is empty, return NULL.
if (this.front == null)
return;
// Store previous front and
// move front one node ahead
this.front = this.front.next;
// If front becomes NULL,
// then change rear also as NULL
if (this.front == null)
this.rear = null;
}
}
// Driver code
public class Test {
public static void Main(String[] args)
{
Queue q = new Queue();
q.enqueue(10);
q.enqueue(20);
q.dequeue();
q.dequeue();
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.dequeue();
Console.WriteLine("Queue Front : " + ((q.front != null) ? (q.front).key : -1));
Console.WriteLine("Queue Rear : " + ((q.rear != null) ? (q.rear).key : -1));
}
}
// This code has been contributed by Rajput-Ji