Singly Linked List Deletion

PHOTO EMBED

Sun May 14 2023 19:17:07 GMT+0000 (Coordinated Universal Time)

Saved by @prachi

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

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

struct node *head = NULL;
struct node *tail = NULL;

int main() {
  int n, node, i;
  struct node *new_node, *current_node;
  struct node *temp = head;
  struct node *pt = NULL;

  printf("Enter the number of nodes: ");
  scanf("%d", &n);

  for (i = 1; i <= n; i++) {
    new_node = (struct node *)malloc(sizeof(struct node));
    printf("Enter the data for node %d: ", i);
    scanf("%d", &new_node->data);

    if (head == NULL) {
      head = new_node;
      tail = head;
    } else {
      tail->next = new_node;
      tail = new_node;
    }
  }

  current_node = head;
  printf("The linked list is:\n");
  while (current_node != NULL) {
    printf("%d -> ", current_node->data);
    current_node = current_node->next;
  }
  printf("NULL\n");

  printf("Enter the node number you want to delete: ");
  scanf("%d", &node);

  temp = head; // Initialize temp to head before traversing the list

  for (i = 1; i < node; i++) {
    pt = temp;
    temp = temp->next;
  }

  if (temp == head) {
    head = temp->next;
  } else if (temp == tail) {
    tail = pt;
    tail->next = NULL;
  } else {
    pt->next = temp->next;
  }

  free(temp);

  current_node = head;
  printf("The linked list after deletion is:\n");
  while (current_node != NULL) {
    printf("%d -> ", current_node->data);
    current_node = current_node->next;
  }
  printf("NULL\n");

  return 0;
}
content_copyCOPY