Insert linked list node at nth last position in c++

C++ program for Insert linked list node at nth last position.Here problem description and explanation.

// Include header file
#include <iostream>
using namespace std;
// C++ program for
// Insert linked list node at nth last position 

// Linked list node
class LinkNode
{
	public: int data;
	LinkNode *next;
	LinkNode(int data)
	{
		this->data = data;
		this->next = nullptr;
	}
};
class LinkedList
{
	public: LinkNode *head;
	LinkedList()
	{
		this->head = nullptr;
	}
	// insert node at end position
	void insert(int value)
	{
		// Create a new node
		LinkNode *node = new LinkNode(value);
		if (this->head == nullptr)
		{
			this->head = node;
		}
		else
		{
			LinkNode *temp = this->head;
			// Find the last node
			while (temp->next != nullptr)
			{
				// Visit to next node
				temp = temp->next;
			}
			// Add node
			temp->next = 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;
	}
	// Add node at specific position from the end of linked list
	void endPosition(int position, int value)
	{
		if (this->head == nullptr)
		{
			cout << "Empty Linked list" << endl;
		}
		else if (position <= 0)
		{
			cout << "Invalid position" << endl;
		}
		else
		{
			LinkNode *temp = this->head;
			LinkNode *location = nullptr;
			while (temp != nullptr)
			{
				position--;
				if (position <= 0)
				{
					if (location == nullptr)
					{
						location = this->head;
					}
					else
					{
						location = location->next;
					}
				}
				// visit to next node
				temp = temp->next;
			}
			if (position <= 1)
			{
				LinkNode *node = new LinkNode(value);
				if (location == nullptr)
				{
					// Add node at first place
					node->next = this->head;
					this->head = node;
				}
				else
				{
					// Add node at intermediate position
					node->next = location->next;
					location->next = node;
				}
			}
			else
			{
				cout << "Opps position not found" << endl;
			}
		}
	}
};
int main()
{
	LinkedList *sll = new LinkedList();
	// Add node
	sll->insert(5);
	sll->insert(4);
	sll->insert(3);
	sll->insert(2);
	sll->insert(1);
	sll->display();
	int position = 2;
	int data = 10;
	sll->endPosition(position, data);
	cout << " Add " << data << " at last " 
         << position << "-nd position" << endl;
	sll->display();
	return 0;
}

Output

5 → 4 → 3 → 2 → 1 → NULL
 Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 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