Skip to main content

Find the smallest number in the doubly linked list in c++

C++ program for Find the smallest number in the doubly linked list. Here problem description and other solutions.

// Include header file
#include <iostream>
using namespace std;
// C++ program for
// Find the smallest node in doubly linked list

// Linked List Node
class LinkNode
{
	public: int data;
	LinkNode *next;
	LinkNode *prev;
	LinkNode(int data)
	{
		this->data = data;
		this->next = nullptr;
		this->prev = nullptr;
	}
};
class DoublyLinkedList
{
	public: 
    LinkNode *head;
	LinkNode *tail;
	DoublyLinkedList()
	{
		this->head = nullptr;
		this->tail = nullptr;
	}
	// Insert new node at end position
	void insert(int value)
	{
		// Create a node
		LinkNode *node = new LinkNode(value);
		if (this->head == nullptr)
		{
			// Add first node
			this->head = node;
			this->tail = node;
			return;
		}
		// Add node at last position
		this->tail->next = node;
		node->prev = this->tail;
		// new last node
		this->tail = node;
	}
	// Find smallest number
	void minNumber()
	{
		if (this->head == nullptr)
		{
			cout << "Empty Linked List" << endl;
		}
		else
		{
			// Get first node of linked list
			LinkNode *temp = this->head;
			int result = temp->data;
			// iterate linked list 
			while (temp != nullptr)
			{
				if (temp->data < result)
				{
					// Get new minimum
					result = temp->data;
				}
				// Visit to next node
				temp = temp->next;
			}
			cout << "Smallest : " << result << endl;
		}
	}
};
int main()
{
	DoublyLinkedList *dll = new DoublyLinkedList();
	// Insert following linked list nodes
	dll->insert(14);
	dll->insert(31);
	dll->insert(12);
	dll->insert(15);
	dll->insert(11);
	dll->insert(25);
	dll->minNumber();
	return 0;
}

Output

Smallest : 11




Comment

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