Skip to content

Instantly share code, notes, and snippets.

@Ajay-Raj-S
Last active September 17, 2019 16:19
Show Gist options
  • Save Ajay-Raj-S/9755f847a81eefd67c00a464abb786d4 to your computer and use it in GitHub Desktop.
Save Ajay-Raj-S/9755f847a81eefd67c00a464abb786d4 to your computer and use it in GitHub Desktop.
A simple and explained code on singly linked list.
#include<stdio.h>
#include<stdlib.h>
struct list {
int value;
struct list* next;
};
struct list* root = NULL;
struct list* lastNodeAddr = NULL;
struct list* nodeCreation(int value) {
struct list* temp = (struct list*) malloc(sizeof(struct list));
temp->value = value;
temp->next = NULL;
return temp;
}
void insertInTheList(struct list* temp) {
if(root == NULL) {
root = temp;
lastNodeAddr = root;
} else {
lastNodeAddr->next = temp;
lastNodeAddr = temp;
}
}
void showTheList(struct list* head) {
if(root == NULL) {
printf("List is empty!\n");
return;
}
while(head != NULL) {
printf("->%d\n", head->value);
head = head->next;
}
}
void destroyTheList(struct list* head) {
if(head != NULL) {
destroyTheList(head->next);
if(root == head) {
root = NULL;
} else {
free(head);
}
}
}
void deleteTheNode(int deleteValue) {
struct list* iterator = root;
struct list* previousNode = root;
while(iterator != NULL) {
if(iterator->value == deleteValue) {
if(iterator->next == NULL) {
previousNode->next = NULL;
} else {
previousNode->next = iterator->next;
}
if(previousNode == root) {
root = iterator->next;
}
if(lastNodeAddr == iterator) {
lastNodeAddr = previousNode;
}
struct list* temporaryHolder = iterator;
iterator = iterator->next;
free(temporaryHolder);
} else {
previousNode = iterator;
iterator = iterator->next;
}
}
}
int main() {
int choice;
int localVal = 0;
int deleteChoice = -1;
int deleteNode = 0;
while(1) {
printf("1.Insert a Node\n2.show the list\n3.Deletion\n");
scanf("%d",&choice);
switch(choice) {
case 1:
printf("Enter the Number: ");
scanf("%d", &localVal);
insertInTheList(nodeCreation(localVal));
break;
case 2:
showTheList(root);
break;
case 3:
printf("Do you want to delete the entire List or a Node ? 1 : 0 ");
scanf("%d", &deleteChoice);
if(deleteChoice) {
if(root == NULL)
printf("List is empty!\n");
else
destroyTheList(root);
} else {
if(root == NULL) {
printf("List is empty!\n");
break;
}
printf("Enter the Number in the Node");
scanf("%d", &deleteNode);
deleteTheNode(deleteNode);
}
break;
default:
printf("wrong choice\n");
destroyTheList(root);
printf("Destroyed The list");
exit(0);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment