Mon Jun 25 2018
Singly Linked list
C Programming1960 views
File Name: singly-linkedlist.c
#include<stdio.h>
#include<stdlib.h>
/* Linked list structure */
struct linkedlist {
int data;
struct linkedlist *next;
} *node = NULL, *first = NULL, *last = NULL, *node1 = NULL;
/* Function for create/insert node in Linked list */
void insert() {
/* Dynamic memory allocation */
node = (struct linkedlist*)malloc(sizeof(struct linkedlist));
printf("Enter value for the node:\n");
scanf("%d",&node->data);
if(first == NULL) {
node->next = NULL;
first = node;
last = node;
printf("Linked list Created!\n");
}
else {
node->next = NULL;
last->next = node;
last = node;
printf("Data Inserted in the Linked list!\n");
}
}
/* Function for Display Linked list */
void display() {
node = first;
printf("List of data in Linked list\n");
while(node != NULL) {
printf("%d\n",node->data);
node = node->next;
}
}
/* Function for delete node from Linked list */
void delete() {
int count = 0, number, i;
node = node1 = first;
for(node = first; node != NULL; node = node->next)
count++;
display();
printf("\n%d nodes available here!\n", count);
printf("Enter the node number which you want to delete:\n");
scanf("%d", &number);
if(number != 1) {
if(number <= count) {
for(i = 2; i <= number; i++)
node = node->next;
for(i = 2; i <= number-1; i++)
node1 = node1->next;
node1->next = node->next;
node->next = NULL;
free(node);
}
else
printf("Invalid node number!\n");
}
else {
first = node->next;
free(node);
}
printf("Node has been deleted successfully!\n");
}
int main() {
int op = 0;
while(op != 4) {
printf("1. Insert 2. Delete 3. Display 4. Exit\n");
printf("Enter your choice:\n");
scanf("%d", &op);
switch(op) {
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
printf("Bye Bye!\n");
exit(0);
break;
default:
printf("Invalid choice!\n");
}
}
return 0;
}
/* Output */
1. Insert2. Delete3. Display4. Exit
Enter your choice:
1
Enter value for the node:
5
Linked list Created!
1. Insert2. Delete3. Display4. Exit
Enter your choice:
1
Enter value for the node:
6
Data Inserted in the Linked list!
1. Insert2. Delete3. Display4. Exit
Enter your choice:
3
List of data in Linked list
5
6
1. Insert2. Delete3. Display4. Exit
Enter your choice:
2
List of data in Linked list
5
6
2 nodes available here!
Enter the node number which you want to delete:
2
Node has been deleted successfully!
1. Insert2. Delete3. Display4. Exit
Enter your choice:
4
Bye Bye!
Reference:
Author:Geekboots