Delete middle node from linked list in cpp

C++ program for Delete middle node from linked list. Here problem description and explanation.

// Include header file
#include <iostream>
using namespace std;
/*
    C++ program for
    Delete middle node of 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;
	}
	// Adding new node at beginning of linked list
	void addNode(int data)
	{
		// Create new node
		LinkNode *node = new LinkNode(data);
		// Connect current node to previous head
		node->next = this->head;
		this->head = node;
	}
	// Display linked list element
	void display()
	{
		if (this->head == nullptr)
		{
			return;
		}
		LinkNode *temp = this->head;
		// iterating linked list elements
		while (temp != nullptr)
		{
			// Display node value
			cout << " " << temp->data << " →";
			// Visit to next node
			temp = temp->next;
		}
		cout << " NULL\n";
	}
	// Delete the middle node of linked list
	void deleteMid()
	{
		if (this->head == nullptr)
		{
			// When linked list are no elements
			cout << "Empty Linked List" << endl;
		}
		else if (this->head->next == nullptr && 
                 this->head->next->next == nullptr)
		{
			// When linked list are less than  of 3 nodes
			cout << "Less then 3 node of linked list" << endl;
		}
		else
		{
			LinkNode *temp = this->head;
			LinkNode *midPrevious = nullptr;
			// Find the middle and its previous node
			while (temp != nullptr && temp->next != nullptr && 
                   temp->next->next != nullptr)
			{
				if (midPrevious == nullptr)
				{
					// When first node
					midPrevious = temp;
				}
				else
				{
					// Visit to next node
					midPrevious = midPrevious->next;
				}
				// Visit to next second next node
				temp = temp->next->next;
			}
			// Get the node which is deleting 
			temp = midPrevious->next;
			// Show deleted node
			cout << "Delete node : " << temp->data << endl;
			// Change link
			midPrevious->next = temp->next;
          	
          	delete temp;
		}
	}
};
int main()
{
	SingleLL *sll = new SingleLL();
	// Linked list
	// 7 → 6 → 5 → 4 → 3 → 2 → 1 → NULL
	sll->addNode(1);
	sll->addNode(2);
	sll->addNode(3);
	sll->addNode(4);
	sll->addNode(5);
	sll->addNode(6);
	sll->addNode(7);
	cout << "Before Delete middle node" << endl;
	sll->display();
	// Delete middle node
	sll->deleteMid();
	cout << "After Delete middle node" << endl;
	sll->display();
	return 0;
}

Output

Before Delete middle node
 7 → 6 → 5 → 4 → 3 → 2 → 1 → NULL
Delete node : 4
After Delete middle node
 7 → 6 → 5 → 3 → 2 → 1 → 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