Sorted order insertion of linked list in c++

C++ program for Sorted order insertion of linked list. Here problem description and explanation.

// Include header file
#include <iostream>
using namespace std;
/*
    C++ program for
    Add node in sorted order 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;
	}
	// Add new node in sorted order
	void sortedAdd(int data)
	{
		// Create new node
		LinkNode *node = new LinkNode(data);
		if (this->head == nullptr || 
            this->head->data >= data)
		{
			// When linked list empty
			// or new nodes are adding at beginning
			node->next = this->head;
			this->head = node;
		}
		else
		{
			LinkNode *temp = this->head;
			// Find position to add new node
			while (temp->next != nullptr && 
                   temp->next->data < data)
			{
				// Visit to next node
				temp = temp->next;
			}
			node->next = temp->next;
			// Add new 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\n";
	}
};
int main()
{
	SingleLL *sll = new SingleLL();
	// Add Linked list node
	sll->sortedAdd(1);
	sll->sortedAdd(-3);
	sll->sortedAdd(9);
	sll->sortedAdd(4);
	sll->sortedAdd(11);
	sll->sortedAdd(-7);
	cout << " Linked List \n";
	// -7 → -3 → 1 → 4 → 9 → 11 → NULL
	sll->display();
	return 0;
}

Output

 Linked List
-7 → -3 → 1 → 4 → 9 → 11 → 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