Implementation of Singly Linked List: Ex - No:1.a
Implementation of Singly Linked List: Ex - No:1.a
Aim:
To write a c program to implement singly linked list.
Algorithm:
Step 1: Define the structure node with data and link Step 2: Display linked list operations insert, delete and display the result. Step 3: If choice is 1 the read element to be inserted and call the insert function Step 4: If choice is 2 then read element to be deleted and call the delete function Step 5: If choice is 3 then call display function Step 6: If choice is 4 then exit the program.
Program:
#include<stdio.h> #include<conio.h> #include<stdlib.h> #define NULL 0 typedef struct list { int no; struct list *next; }LIST; LIST *p,*t,*h,*y,*ptr,*pt; void create( void ); void insert( void ); void delet( void ); void display ( void ); int j,pos,k=1,count; void main() { int n,i = 1,opt; clrscr(); p = NULL; printf( "Enter the no of nodes :\n " ); scanf( "%d",&n ); count = n; while( i <= n) { create(); i++; } printf("\nEnter your option:\n"); printf("1.Insert \t 2.Delete \t 3.Display \t 4.Exit\n"); do { scanf("%d",&opt); switch( opt ) { case 1: insert(); count++; break; case 2: delet(); count--;
if ( count == 0 ) { printf("\n List is empty\n"); } break; case 3: printf("List elements are:\n"); display(); break; } printf("\nEnter your option \n"); }while( opt != 4 ); getch(); } void create ( ) { if( p == NULL ) { p = ( LIST * ) malloc ( sizeof ( LIST ) ); printf( "Enter the element:\n" ); scanf( "%d",&p->no ); p->next = NULL; h = p; } else { t = ( LIST * ) malloc (sizeof( LIST )); printf( "\nEnter the element" ); scanf( "%d",&t->no ); t->next = NULL; p->next = t; p = t; } } void insert() { t=h; p = ( LIST * ) malloc ( sizeof(LIST) ); printf("Enter the element to be inserted:\n"); scanf("%d",&p->no); printf("Enter the position to insert:\n"); scanf( "%d",&pos );
else { for(j=1;j<(pos-1);j++) t = t->next; p->next = t->next; t->next = p; t=p; } } void delet() { printf("Enter the position to delete:\n"); scanf( "%d",&pos ); if( pos == 1 ) { h = h->next ; } else { t = h; for(j=1;j<(pos-1);j++) t = t->next; pt=t->next->next; free(t->next); t->next= pt; } } void display() { t = h; while( t->next != NULL ) { printf("\t%d",t->no); t = t->next; } printf( "\t %d\t",t->no ); }
Output:
Enter the no of nodes: 3 Enter the element:1 Enter the element:2 Enter the element:3 Enter your option: 1. Insert 2.Delete 3.Display 1 Enter the element to be inserted:4 Enter the position to insert:4 Enter your option 3 List elements are: 1 2 3 4 Enter your option 2 Enter the position to delete:3 Enter your option 3 List elements are: 1 2 4 Enter your option 4
4.Exit