Count frequency of a key in doubly linked list in c++
C++ program for Count frequency of a key in doubly linked list. Here problem description and other solutions.
// Include header file
#include <iostream>
using namespace std;
// C++ program for
// Count frequency of given node in doubly linked list
class LinkNode
{
public: int data;
LinkNode *next;
LinkNode *prev;
LinkNode(int data)
{
this->data = data;
this->next = nullptr;
this->prev = nullptr;
}
};
class DoublyLinkedList
{
public: LinkNode *head;
LinkNode *tail;
DoublyLinkedList()
{
this->head = nullptr;
this->tail = nullptr;
}
// Insert new node at end position
void insert(int value)
{
// Create a node
LinkNode *node = new LinkNode(value);
if (this->head == nullptr)
{
// Add first node
this->head = node;
this->tail = node;
return;
}
// Add node at last position
this->tail->next = node;
node->prev = this->tail;
this->tail = node;
}
// Display node element of doubly linked list
void display()
{
if (this->head == nullptr)
{
cout << "Empty Linked List" << endl;
}
else
{
cout << "Linked List Head to Tail :";
// Get first node of linked list
LinkNode *temp = this->head;
// iterate linked list
while (temp != nullptr)
{
// Display node value
cout << " " << temp->data;
// Visit to next node
temp = temp->next;
}
cout << "\nLinked List Tail to Head :";
// Get last node of linked list
temp = this->tail;
// iterate linked list
while (temp != nullptr)
{
// Display node value
cout << " " << temp->data;
// Visit to prev node
temp = temp->prev;
}
cout << "\n";
}
}
// Count frequency of given node
void frequency(int key)
{
int result = 0;
LinkNode *temp = this->head;
while (temp != nullptr)
{
if (temp->data == key)
{
// count key
result++;
}
// Visit to next node
temp = temp->next;
}
// Print result
cout << "Frequency of node " << key
<< " is : " << result << endl;
}
};
int main()
{
DoublyLinkedList *dll = new DoublyLinkedList();
// Insert following linked list nodes
dll->insert(7);
dll->insert(2);
dll->insert(3);
dll->insert(4);
dll->insert(5);
dll->insert(3);
dll->insert(7);
dll->insert(3);
//display all node
dll->display();
dll->frequency(3);
dll->frequency(11);
dll->frequency(7);
return 0;
}
Output
Linked List Head to Tail : 7 2 3 4 5 3 7 3
Linked List Tail to Head : 3 7 3 5 4 3 2 7
Frequency of node 3 is : 3
Frequency of node 11 is : 0
Frequency of node 7 is : 2
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment