Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct node{
- int data;
- struct node* next;
- } *head = NULL;
- int display(){
- if(!head) printf("Linked List is empty!");
- else{
- struct node* help = head;
- printf("| %d |-->",help);
- while (help != NULL){
- printf("| %d | %d |-->", help->data, help->next);
- help = help -> next;
- }
- }
- }
- void insert(int value){
- struct node *newNode = (struct node*) malloc(sizeof(struct node*));//Create space for new node
- newNode->data = value;
- if(!head || value <= head->data){ //Inserting in the front
- if(head) newNode->next = head;
- else newNode->next = NULL;
- head = newNode;
- } else{
- struct node *help = head, *prev = NULL;
- while(help && value > help->data){
- prev = help;
- help = help ->next; //Traverse linked list
- }
- newNode->next = help; //Inserting in middle or to the back
- prev->next = newNode;
- }
- }
- void remove(int value){
- struct node* help = head, *prev = NULL;
- while(help){//Traversal until match found
- if(help->data == value) break;
- prev = help;
- help = help->next;
- }
- if(!help) printf("\nValue not Found.\n");
- else{
- struct node *target = help;//target is the node to be deleted
- if(target == head) head = head->next;//deleting from front
- else prev->next = target->next;//deleting from the middle/end
- free(target);
- }
- }
- int main(){
- int n;
- while(1){
- display();
- printf("\n\n1. Instert 2. Delete 3. Exit: ");
- scanf("%d", &n);
- switch(n){
- case 1:
- printf("\nEnter an element to insert: ");
- scanf("%d", &n);
- insert(n);
- break;
- case 2:
- if(head){
- printf("\nEnter an Element to delete: ");
- scanf("%d", &n);
- remove(n);
- }
- break;
- default:
- printf("\nTry again.\n");
- break;
- case 3:
- printf("\nMore programs @ pastebin.com/u/ShailRShah");
- return 0;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement