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 more information.

// Include header file
#include <stdio.h>
#include <stdlib.h>
// C program for
// Find the smallest node in doubly linked list

// Linked List Node
typedef struct LinkNode
{
	// Define useful field of LinkNode
	int data;
	struct LinkNode * next;
	struct LinkNode * prev;
}LinkNode;

LinkNode * getLinkNode(int data)
{
	// Create dynamic memory of LinkNode
	LinkNode * ref = (LinkNode * ) malloc(sizeof(LinkNode));
	if (ref == NULL)
	{
		// Failed to create memory 
		return NULL;
	}
	ref->data = data;
	ref->next = NULL;
	ref->prev = NULL;
	return ref;
}
typedef struct DoublyLinkedList
{
	// Define useful field of DoublyLinkedList
	struct LinkNode * head;
	struct LinkNode * tail;
}DoublyLinkedList;

DoublyLinkedList * getDoublyLinkedList()
{
	// Create dynamic memory of DoublyLinkedList
	DoublyLinkedList * ref = 
      (DoublyLinkedList * ) malloc(sizeof(DoublyLinkedList));
	if (ref == NULL)
	{
		// Failed to create memory 
		return NULL;
	}
	// Set inital value
	ref->head = NULL;
	ref->tail = NULL;
	return ref;
}
// Insert new node at end position
void insert(DoublyLinkedList * ref, int value)
{
	// Create a node
	LinkNode * node = getLinkNode(value);
	if ((ref->head == NULL))
	{
		// Add first node
		ref->head = node;
		ref->tail = node;
		return;
	}
	// Add node at last position
	ref->tail->next = node;
	node->prev = ref->tail;
	// new last node
	ref->tail = node;
}
// Find smallest number
void minNumber(DoublyLinkedList * ref)
{
	if ((ref->head == NULL))
	{
		printf("Empty Linked List");
	}
	else
	{
		// Get first node of linked list
		LinkNode * temp = ref->head;
		int result = temp->data;
		// iterate linked list 
		while (temp != NULL)
		{
			if ((temp->data < result))
			{
				// Get new minimum
				result = temp->data;
			}
			// Visit to next node
			temp = temp->next;
		}
		printf("Smallest : %d", result);
	}
}
int main()
{
	DoublyLinkedList * dll = getDoublyLinkedList();
	// Insert following linked list nodes
	insert(dll, 14);
	insert(dll, 31);
	insert(dll, 12);
	insert(dll, 15);
	insert(dll, 11);
	insert(dll, 25);
	minNumber(dll);
}

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