Doubly Linked List Insertion

PHOTO EMBED

Sun May 14 2023 19:23:32 GMT+0000 (Coordinated Universal Time)

Saved by @prachi

#include <stdio.h>
#include <stdlib.h>

struct node {
	int data;
	struct node *prev, *next;
};
struct node* head = NULL;

void display()
{
	if (head == NULL) {
		printf("\nList is empty\n");
		return;
	}
	struct node* temp;
	temp = head;
	while (temp != NULL) {
		printf("Data = %d\n", temp->data);
		temp = temp->next;
	}
}

void insertAtFront()
{
	int n;
	struct node* temp;
	temp = (struct node*)malloc(sizeof(struct node));
	printf("\nEnter number to be inserted: ");
	scanf("%d", &n);
	temp->data = n;
	temp->prev = NULL;
	temp->next = head;
	head = temp;
}

void insertAtEnd()
{
	int n;
	struct node *temp, *ptr;
	temp = (struct node*)malloc(sizeof(struct node));
	temp->prev = NULL;
	temp->next = NULL;
	printf("\nEnter number to be inserted: ");
	scanf("%d", &n);
	temp->data = n;
	temp->next = NULL;
	ptr = head;


	if (head == NULL) {

	head = temp;
	}

	else {
		while (ptr->next != NULL)
			ptr = ptr->next;
		temp->prev = ptr;
		ptr->next = temp;
	}
}

void insertAtPosition()
{
	int n, pos, i = 1;
	struct node *temp, *newnode;
	newnode = malloc(sizeof(struct node));
	newnode->next = NULL;
	newnode->prev = NULL;

	printf("\nEnter position : ");
	scanf("%d", &pos);
	

	if (head == NULL) {
		head = newnode;
		newnode->prev = NULL;
		newnode->next = NULL;
	}
	else if (pos == 1) {
	insertAtFront();
	}

	else {
	printf("\nEnter number to be inserted: ");
	scanf("%d", &n);
	newnode->data = n;
	temp = head;
		while (i < pos - 1) {
			temp = temp->next;
			i++;
		}
		newnode->next = temp->next;
		newnode->prev = temp;
		temp->next = newnode;
		temp->next->prev = newnode;
	}
}



// Driver Code
int main()
{
	int choice;
	while (1) {

	printf("\n1.Insert at beginning\n2.Insert in middle\n3.Insert at end\n4.Exit\nEnter your choice: ");
		scanf("%d", &choice);

		switch (choice) {
		
		case 1:
			insertAtFront();
			display();
			break;
		case 2:
		insertAtPosition();
			display();
			break;
		case 3:
			insertAtEnd();
			display();
			break;
		
		case 4:
			exit(1);
			break;
		default:
			printf("Invalid Choice\n");
			continue;
		}
	}
	return 0;
}
content_copyCOPY