Data Structure Lecture 4
Data Structure Lecture 4
Lecture 4
Queue
Dr. Mohamed Eassa 1
Queue
First-in First-out
2
Queue
First-in First-out
3
Queue Operations
Enqueue (): Inserts an element at the end of the queue.
Peak (): Get the element at the front without removing it from the queue.
isEmpty: Determines whether the queue is empty. If the queue is empty, it returns the value
true; otherwise, it returns the value false.
isFull: Determines whether the queue is full. If the queue is full, it returns the value true;
otherwise, it returns the value false.
5
Linked List Implementation of queue
• Create a linked list to which items would be added to one end and deleted from the
other end.
• Two pointers will be maintained:
• One pointing to the beginning of the list (point from where elements will be
deleted).
• Another pointing to the end of the list (point where new elements will be
inserted). Rear
8
Display Operation
void display ()
{
If (isEmpty())
cout << “Queue is empty \n”;
else
{
node* temp = front;
while (temp!= NULL)
{
cout << temp->data<<“ \t”;
temp = temp -> next;
}
cout << endl;
}
} 9
main function
int main()
{
Queue q;
int item;
for (int i =0; i < 3 ; i++)
{
cout << “Enter Item to Enqueu\n”;
cin >> item;
q.enqueu (item);
}
q.display();
10
Dequeue Operation
Int Dequeue ()
{
int delitem= 0;
if (isEmpty()) (1) Queue is empty
cout<< “the queue is empty \n”;
else if (front == rear)
{ front rear
delete front;
front = rear = NULL;
} (2) 10 /
else
{
node* delptr= front;
front= front-> next; delptr front rear
delitem = delptr-> data;
delete delptr;
} (3) 10 20 30 /
return delitem;
}
11
main function
int main()
{
Queue q;
int item;
for (int i =0; i < 3 ; i++)
{
cout << “Enter Item to Enqueu\n”;
cin >> item;
q.enqueu (item);
}
q.display();
int peak()
13
GetRear Operation
int getRear()
14
Clear function
void clear()
{
while (!isEmpty())
Dequeue();
15
main function
int main()
{
Queue q;
int item;
for (int i =0; i < 3 ; i++)
{
cout << “Enter Item to Enqueu\n”;
cin >> item;
q.enqueu (item);
}
q.display();
int count()
{
int counter = 0;
node* temp = front;
while (temp!= NULL)
{
counter++;
temp = temp -> next;
}
return counter;
}
17
Search function
bool isFound (int item)
{
bool found = false;
node* temp = front;
while(temp!= NULL)
{
If (temp -> data == item)
found = true;
temp = temp->next;
}
return found;
} 18