Remove every k th node of the linked list in c++

C++ program for Remove every k th node of the linked list. Here problem description and explanation.

// Include header file
#include <iostream>
using namespace std;
// C++ Program for
// delete every k-th node of the 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;
	SingleLL()
	{
		this->head = nullptr;
	}
	// Add new node at the end of linked list
	void addNode(int value)
	{
		// Create  node
		LinkNode *node = new LinkNode(value);
		if (this->head == nullptr)
		{
			this->head = node;
		}
		else
		{
			LinkNode *temp = this->head;
			// Find last node
			while (temp->next != nullptr)
			{
				// Visit to next node
				temp = temp->next;
			}
			// Add node at last position
			temp->next = node;
		}
	}
	// Display all Linked List elements
	void display()
	{
		if (this->head != nullptr)
		{
			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\n" << endl;
		}
	}
	void removeKh(int kth)
	{
		if (this->head == nullptr)
		{
			// When no element
			cout << "Empty Linked list" << endl;
		}
		else if (kth <= 0)
		{
			cout << "\nInvalid position " << kth << endl;
		}
		else
		{
			LinkNode *temp = this->head;
			LinkNode *hold = nullptr;
			LinkNode *checker = nullptr;
			int count = 0;
			if (kth == 1)
			{
				// When delete all element
				this->head = nullptr;
			}
			while (temp != nullptr)
			{
				count++;
				if (count % kth == 0)
				{
					// When delete node found
					hold = temp;
				}
				else
				{
					// Get current node
					checker = temp;
				}
				temp = temp->next;
				// When get free node
				if (hold != nullptr)
				{
					if (checker != nullptr)
					{
						// Unlink node
						checker->next = hold->next;
					}
                  	delete hold;
					hold = nullptr;
				}
			}
		}
	}
};
int main()
{
	SingleLL *sll = new SingleLL();
	// Linked list
	// 1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
	sll->addNode(1);
	sll->addNode(2);
	sll->addNode(3);
	sll->addNode(4);
	sll->addNode(5);
	sll->addNode(6);
	sll->addNode(7);
	int position = 2;
	cout << "Position : " << position << endl;
	cout << "Before Delete Linked List" << endl;
	sll->display();
	sll->removeKh(position);
	cout << "\n After Linked List" << endl;
	sll->display();
	return 0;
}

Output

Position : 2
Before Delete Linked List
  1  2  3  4  5  6  7
 After Linked List
  1  3  5  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