From e211a1d20a2b5467765fb5ebcc9e1fe4d51192fc Mon Sep 17 00:00:00 2001 From: Tawfik Yasser Date: Sun, 7 Mar 2021 18:47:15 +0200 Subject: [PATCH] Queue linked-list Added (#100) * Queue linked-.list Added * Update queue-linked-list.cpp * Update queue-linked-list.cpp --- queues/README.md | 5 ++ queues/c-or-cpp/queue-linked-list.cpp | 101 ++++++++++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 queues/README.md create mode 100644 queues/c-or-cpp/queue-linked-list.cpp diff --git a/queues/README.md b/queues/README.md new file mode 100644 index 00000000..a8df0f15 --- /dev/null +++ b/queues/README.md @@ -0,0 +1,5 @@ +# Queues + +### C or C++ + +1. [Queue using linked list](c-or-cpp/queue-linked-list.cpp) diff --git a/queues/c-or-cpp/queue-linked-list.cpp b/queues/c-or-cpp/queue-linked-list.cpp new file mode 100644 index 00000000..d6c9dc28 --- /dev/null +++ b/queues/c-or-cpp/queue-linked-list.cpp @@ -0,0 +1,101 @@ +// Content: Queue using linked list (FIFO) +// Author: Tawfik Yasser +// Date: Fri, 5 Mar 2021 + +#include +using namespace std; +// Class `Node` to represent every item in the queue +class Node +{ +public: + int data; // Item data + Node *next; // Pointer to next item + Node() {} // Empty constructor +}; +// Claas to represent the queue using linked list +class QueueLL +{ +private: + Node *front; // Pointer to the head of the queue + Node *rear; // Pointer to the end of the queue + int _length; +public: + QueueLL() //Empty constructor to initialize front and rear to NULL because in the start the queue will be empty + { + front = rear = NULL; + _length = 0 ; + } + + // Function `Enqueue` to add new item to the queue from the rear side (End) + void enqueue(int value) + { + Node *newNode = new Node(); + newNode->data = value; + newNode->next = NULL; + if(front == NULL && rear == NULL) // Empty queue + { + front = rear = newNode; + } + else + { + rear->next = newNode; + rear = newNode; + } + _length++; + } + + // Function `Dequeue` to remove an item from the queue from the front side (Start) + void dequeue() + { + Node *temp = front; + front = front->next; + delete temp; //Free the memory + _length--; + } + + // Function `Peek` to return the first item in the queue + void peek() + { + cout<data<data<<" ] "; + temp = temp->next; + } + } + } + int _size() + { + return _length; + } +}; +int main() +{ + //Test the functions + QueueLL qll; + qll.enqueue(5); + qll.enqueue(3); + qll.enqueue(-2); + qll.print(); + cout<