Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Linked List #include<stdio.h> #include<conio.

h> void main ()

int op;

createlist(); while(1) { printf("Single Linked List \n"); printf("1.INSERT \n"); printf("2.DELETE \n"); printf("3.DISPLAY \n"); printf("4.EXIT \n"); printf("Enter Your Option:\n"); scanf("%d",&op);

switch(op) { case 1: insert(); break; case 2: delete(); break; case 3: display();break; case 4: exit(0); default: printf("INVALID OPTION !! \n");

getch (); } }

struct node

{ int data; struct node *link;

};

struct node*head;

void createlist() {

struct node*cur,*ptr; int ele; head = NULL;

printf(" Enter an element: \n"); scanf("%d",&ele);

while (ele != -1)

cur = (struct node*)malloc (sizeof (struct node));

cur->data = ele; cur->link = NULL;

if (head==NULL) head = cur;

else

ptr->link = cur; ptr = cur;

printf("Enter an element : \n"); scanf("%d", & ele);

} }

void insert() {

struct node*cur,*ptr; int ele; char ch;

ptr = head;

printf(" Enter an element: \n"); scanf("%d",&ele); cur = (struct node*)malloc (sizeof (struct node));

cur->data = ele; cur->link = NULL;

fflush(stdin); // to clear input stream buffer

printf("Do you want to insert at the first position (Y/n): \n"); scanf("%c",&ch);

if(ch=='y'|| ch =='Y')

{ cur->link = head; head = cur;

else

printf("After which node you want to insert the element:"); scanf("%d",&ele);

while(ptr!=NULL) { if (ptr->data == ele) { cur->link = ptr->link; ptr->link = cur; break;

else

{ ptr = ptr->link; }

void delete ()

{ struct node*ptr,*ptr1; int ele; char ch; ptr = head; fflush(stdin);

printf("Do you want to delete the first node (Y/N):\n"); scanf("%c",&ch);

if(ch=='Y' || ch =='y')

{ head = ptr->link; free(ptr); }

else { printf("Which node do you want to delete :\n"); scanf("%d",&ele); while(ptr!=NULL) {

if(ptr->link->data == ele)

{ ptr1=ptr->link; ptr->link = ptr1->link; free(ptr1); break;

else

{ ptr = ptr->link; }

} } void display () { struct node *ptr; ptr = head;

if(head==NULL)

printf("No elements in the list /n");

else

{ printf("Single Linked List Elements:\n HEAD");

while(ptr!=NULL)

printf("-> %d",ptr->data); ptr = ptr->link;

printf("->NULL");

} }

You might also like