Delete duplicate nodes from sorted linked list in c++

C++ program for Delete duplicate nodes from sorted linked list. Here problem description and explanation.

// Include header file
#include <iostream>
using namespace std;
/*
    C++ program for
    Delete duplicate nodes in sorted linked list
*/
// Linked list node
class LinkNode
{
	public: int data;
	LinkNode *next;
	LinkNode(int data)
	{
		this->data = data;
		this->next = nullptr;
	}
};
class SingleLL
{
	public: LinkNode *head;
	LinkNode *tail;
	SingleLL()
	{
		this->head = nullptr;
		this->tail = nullptr;
	}
	// Add new node at the end of linked list
	void addNode(int value)
	{
		// Create a new node
		LinkNode *node = new LinkNode(value);
		if (this->head == nullptr)
		{
			this->head = node;
		}
		else
		{
			this->tail->next = node;
		}
		this->tail = node;
	}
	// Display linked list element
	void display()
	{
		if (this->head == nullptr)
		{
			return;
		}
		LinkNode *temp = this->head;
		// iterating linked list elements
		while (temp != nullptr)
		{
			cout << temp->data << " → ";
			// Visit to next node
			temp = temp->next;
		}
		cout << " NULL" << endl;
	}
	// Remove the duplicate nodes from sorted singly linked list
	void deleteDuplicate()
	{
		if (this->head == nullptr)
		{
			return;
		}
		else
		{
			// Auxiliary variables
			LinkNode *temp = this->head->next;
			LinkNode *current = this->head;
			LinkNode *hold = nullptr;
			// Find and remove duplicate
			while (temp != nullptr)
			{
				// Check duplicate node 
				if (current->data == temp->data)
				{
					//  When node key are same
					hold = temp;
				}
				else
				{
					// When node key are not same
					current = temp;
				}
				// Visit to next node
				temp = temp->next;
				if (hold != nullptr)
				{
					// Modified link value
					current->next = temp;
					hold = nullptr;
				}
				else
				{
					// Change last node
					this->tail = current;
				}
			}
		}
	}
};
int main()
{
	SingleLL *sll = new SingleLL();
	// Sorted Linked list node
	//  1 → 1 → 2 → 3 → 4 → 4 → 4 → 5 → 6 → 7 → NULL
	sll->addNode(1);
	sll->addNode(1);
	sll->addNode(2);
	sll->addNode(3);
	sll->addNode(4);
	sll->addNode(4);
	sll->addNode(4);
	sll->addNode(5);
	sll->addNode(6);
	sll->addNode(7);
	cout << " Before Delete" << endl;
	sll->display();
	sll->deleteDuplicate();
	cout << " After Delete" << endl;
	// 1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
	sll->display();
	return 0;
}

Output

 Before Delete
1 → 1 → 2 → 3 → 4 → 4 → 4 → 5 → 6 → 7 →  NULL
 After Delete
1 → 2 → 3 → 4 → 5 → 6 → 7 →  NULL


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