ALGORITHM

SOURCE CODE

Linked List Declaration and initialization


#include<stdio.h>
#include<stdlib.h>

struct node{
	int data;
	struct node * next;
};

Traversal/print in Linked List

void linkedlistTraversal(struct node *ptr){
	while (ptr != NULL){
		//prints the element of the linked lists
		printf("Element: %d \\n", ptr -> data);
		ptr = ptr -> next;
	}
}

Linked list Deletion functions

  1. Delete at the starting
struct node * deleteFirst( struct node * head){
    struct node * ptr = head;
    head = head -> next;
    free (ptr);
    return head;
}
  1. Delete in between
struct node * deleteAtIndex ( struct node * head, int index){
    struct node * p = head;
    struct node * q = head -> next;
    for (int i = 0; i < index -1; i++ ){
        p = p -> next;
        q = q -> next;
    }
    p -> next = q -> next;
    free (q);
    return head;
}
  1. Delete by Value
struct node * deleteTheValue(struct node * head, int value){
    struct node * p = head;
    struct node * q = head -> next;
    while ( q->data != value && q->next != NULL)
    {
        p = p -> next;
        q = q -> next;
    }
    if (q->data == value){
        p->next = q->next;
        free(q);
    }
    return head;
}
  1. Delete in the end
struct node * deleteEnd( struct node * head){
    struct node * p = head;
    struct node * q = head -> next;
    while (q -> next != NULL){
        p = p -> next;
        q = q -> next;
    }
    p -> next = NULL;
    free (q);
    return head;
}

Driver Code

int main(){
	// node * xyx (xyz is a Pointer variable)
	struct node * head;
	struct node * second;
	struct node * third;
	struct node * fourth;

	//allocate memory for nodes in HEAP

	head = (struct node *)malloc(sizeof(struct node));
	second = (struct node *)malloc(sizeof(struct node));
	third = (struct node *)malloc(sizeof(struct node));
    fourth = (struct node *)malloc(sizeof(struct node));
	//link nodes '->' arrow operator

	head -> data = 1;
	head -> next = second;
	second -> data = 2;
	second -> next = third;
	third -> data = 3;
	third -> next = fourth;
    fourth -> data = 4;
	fourth -> next = NULL;
    printf("Linked list before deletion: \\n");
	linkedlistTraversal(head);

//uncomment the function call you wanna perform

    //head = deleteFirst(head);
    //head = deleteAtIndex(head, 2); //2 is the index number
    //head = deleteEnd(head);
    //head = deleteTheValue(head, 4);

    printf("Linked list after deletion: \\n");
    linkedlistTraversal(head);

    return 0;
}