Insert node at beginning of doubly linked list in c

C program for Insert node at beginning of doubly linked list. Here problem description and other solutions.

// Include header file
#include <stdio.h>
#include <stdlib.h>
// C Program For
// Insert new node at beginning of doubly linked list

// Define structure of 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 * me = (LinkNode * ) malloc(sizeof(LinkNode));
	if (me == NULL)
	{
		// Failed to create memory 
		return NULL;
	}
	me->data = data;
	me->next = NULL;
	me->prev = NULL;
	return me;
}

typedef struct DoublyLinkedList
{
	// Define useful field of DoublyLinkedList
	struct LinkNode * head;
}DoublyLinkedList;


DoublyLinkedList * getDoublyLinkedList()
{
	// Create dynamic memory of DoublyLinkedList
	DoublyLinkedList * me = 
      (DoublyLinkedList * ) malloc(sizeof(DoublyLinkedList));
	if (me == NULL)
	{
		// Failed to create memory 
		return NULL;
	}
	// Set inital value
	me->head = NULL;
	return me;
}
// Insert new node at beginning position
void insert(DoublyLinkedList * me, int value)
{
	// Create a node
	LinkNode * node = getLinkNode(value);
	node->next = me->head;
	// When linked list is not empty
	if ((me->head != NULL))
	{
		me->head->prev = node;
	}
	// Make new head
	me->head = node;
}
// Display node element of doubly linked list
void display(DoublyLinkedList * me)
{
	if ((me->head == NULL))
	{
		printf("Empty Linked List");
	}
	else
	{
		printf("Doubly Linked List Element : \n");
		// Get first node of linked list
		LinkNode * temp = me->head;
		// Traverse doubly linked list from front to rear
		while (temp != NULL)
		{
			// Display node value
			printf("%d  ", temp->data);
			// Visit to next node
			temp = temp->next;
		}
	}
}
int main()
{
	DoublyLinkedList * dll = getDoublyLinkedList();
	// Insert following linked list nodes
	insert(dll, 70);
	insert(dll, 60);
	insert(dll, 50);
	insert(dll, 40);
	insert(dll, 30);
	insert(dll, 20);
	insert(dll, 10);
	//  NULL <- 10 <--> 20 <--> 30 <--> 40 <--> 50 <--> 60 <--> 70->NULL
	display(dll);
}

Output

Doubly Linked List Element :
10  20  30  40  50  60  70


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