Remove duplicates from unsorted linked list in cpp

C++ program for Remove duplicates from unsorted linked list. Here problem description and explanation.

// Include header file
#include <iostream>

using namespace std;
// C++ Program to 
// Delete duplicate nodes in unsorted linked list
class LinkNode
{
	public: int data;
	LinkNode *next;
	LinkNode(int data)
	{
		this->data = data;
		this->next = nullptr;
	}
};
class LinkedList
{
	public: LinkNode *head;
	LinkNode *tail;
	// Class constructors
	LinkedList()
	{
		this->head = nullptr;
		this->tail = nullptr;
	}
	// Insert new element at end position
	void insert(int value)
	{
		// Create new node
		LinkNode *node = new LinkNode(value);
		if (this->head == nullptr)
		{
			// Add first node
			this->head = node;
		}
		else
		{
			// Add new node at the last position
			this->tail->next = node;
		}
		// Make new tail 
		this->tail = node;
	}
	// Display all node value
	void display()
	{
		if (this->head != nullptr)
		{
			cout << "Linked List Element :";
			LinkNode *temp = this->head;
			while (temp != nullptr)
			{
				// Display node value
				cout << "  " << temp->data;
				// Visit to next node
				temp = temp->next;
			}
		}
		else
		{
			cout << "Empty Linked list" << endl;
		}
	}
	void removeNode()
	{
		if (this->head == nullptr)
		{
			// When linked list empty
			cout << "Empty Linked list";
		}
		else
		{
			// Auxiliary variable
			LinkNode *temp = this->head;
			LinkNode *hold = nullptr;
			LinkNode *initial = nullptr;
			LinkNode *current = nullptr;
			// Outer loop
			while (temp != nullptr)
			{
				current = temp;
				initial = current->next;
				// Inner loop
				// Remove all node which value is similar to temp node
				while (initial != nullptr)
				{
					if (temp->data == initial->data)
					{
						// Get remove node
						hold = initial;
					}
					else
					{
						current = initial;
					}
					// Visit to next node
					initial = initial->next;
					if (hold != nullptr)
					{
						current->next = initial;
						// remove node
						hold = nullptr;
					}
				}
				// Visit to next node
				temp = temp->next;
			}
			// New last node
			this->tail = current;
		}
	}
};
int main()
{
	// new linked list
	LinkedList *task = new LinkedList();
	// Add tested element
	task->insert(1);
	task->insert(2);
	task->insert(9);
	task->insert(4);
	task->insert(9);
	task->insert(3);
	task->insert(1);
	task->insert(7);
	task->insert(2);
	task->insert(1);
	cout << "\nBefore Delete " << endl;
	task->display();
	task->removeNode();
	cout << "\nAfter Delete " << endl;
	task->display();
	return 0;
}

Output

Before Delete
Linked List Element :  1  2  9  4  9  3  1  7  2  1
After Delete
Linked List Element :  1  2  9  4  3  7


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







© 2021, kalkicode.com, All rights reserved