You are on page 1of 3

#include <stdio.

h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head;
void init()
{
head = NULL;
}
void InsertFront(int ele)
{
struct node* newNode = (struct node*) malloc(sizeof(struct
node));
newNode->data = ele;
newNode->next = head;
head = newNode;
}
void InsertRear(int ele)
{
if (head == NULL)
{
printf("Linked list is empty");
return;
}
struct node* newNode =(struct node*) malloc(sizeof(struct
node));
newNode->data = ele;
newNode->next = NULL;
struct node *temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
void DeleteRear()

{
struct node *temp = head, *temp1;
/*
if(head == NULL)
{
printf("\nLinked list is empty");
return;
}
*/
while(temp -> next != NULL)
{
temp1 = temp;
temp = temp -> next;
}
temp1 -> next = NULL;
printf("\nDeleting element %d now", temp -> data);
free(temp);
}
void display(struct node *head) {
printf("\nLinked List\n");
struct node *temp = head;
while (temp != NULL) {
printf("%d", temp->data);
temp = temp->next;
if(temp != NULL)
printf("-->");
}
}
int main()
{
int ele, choice;
init(head);
do
{
printf("\n1.Insert from the front");
printf("\n2.Insert from the rear");
printf("\n3.Delete a node from the rear");
printf("\n4.Display the linked list");

printf("\n5.Exit");
printf("\nEnter your choice (1 - 5): ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("\nEnter the element you wish to insert at
the front: ");
scanf("%d", &ele);
InsertFront(ele);
display(head);
break;
case 2:
printf("\nEnter the element you wish to insert at
the rear: ");
scanf("%d", &ele);
InsertRear(ele);
display(head);
break;
case 3:
DeleteRear();
break;
case 4:
display(head);
break;
case 5: exit(0);
}
}while(choice != 5);
return 0;
}

You might also like