forked from AlbinoB/Data_Structures_With_Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueOperations.java
More file actions
106 lines (70 loc) · 1.56 KB
/
Copy pathQueueOperations.java
File metadata and controls
106 lines (70 loc) · 1.56 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package queue;
import queue.Node;
public class QueueOperations<T>{
private Node<T> head=null;
private Node<T> tail=null;
public void enqueue(T data) {
Node<T> newNode=new Node<T>(data);
if(head==null) {
head=newNode;
tail=head;
}else {
tail.next=newNode;
tail=newNode;
}
}
public T dequeue() {
if(head==null) {
return null;//queue is empty
}else {
T data=head.data;
head=head.next;
return data;//return first element of queue after it has been dequeue
}
}
public T peek() {
if(head==null) {
return null;//queue is empty
}else {
return (T) head.data;//return head element of queue
}
}
public T remove(T data) {
if(peek()==null) {
System.out.println("Queue is empty, cant remove "+data);
return null;
}
Node<T> temp=head;
Node<T> tempPrevious=null;
while(temp!=null)//loop until temp is not null or value is found
{
if(temp.data.equals(data)) {
if(head==temp) {//first element to be removed
head=head.next;
return data;
}
tempPrevious.next=temp.next;
return data;
}else {
tempPrevious=temp;
temp=temp.next;//move to next node
}
}
return null;//not found
}
public boolean isEmpty() {
return head==null;
}
public void displayQueue() {
if(peek()==null) {
System.out.println("Queue is empty");
return;
}
Node<T> temp=head;
while(temp!=null)//loop until temp is not null
{
System.out.println(temp.data);
temp=temp.next;//move to next node
}
}
}