Advertisement
MrAyushBajpai

Deletion in Array Based List

Oct 17th, 2024
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.16 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. // Function to delete an element from the array-based list
  4. void deleteElement(int arr[], int *n, int pos) {
  5.     // Check if the position is valid
  6.     if (pos < 0 || pos >= *n) {
  7.         printf("Invalid position!\n");
  8.         return;
  9.     }
  10.  
  11.     // Shift elements to the left to fill the gap created by deletion
  12.     for (int i = pos; i < *n - 1; i++) {
  13.         arr[i] = arr[i + 1];
  14.     }
  15.  
  16.     // Decrease the size of the list
  17.     (*n)--;
  18.  
  19.     printf("Element deleted successfully.\n");
  20. }
  21.  
  22. // Function to display the list
  23. void displayList(int arr[], int n) {
  24.     printf("List: ");
  25.     for (int i = 0; i < n; i++) {
  26.         printf("%d ", arr[i]);
  27.     }
  28.     printf("\n");
  29. }
  30.  
  31. int main() {
  32.     int arr[100]; // Array-based list of size 100
  33.     int n = 5; // Initial size of the list
  34.  
  35.     // Initialize the list with some elements
  36.     arr[0] = 10;
  37.     arr[1] = 20;
  38.     arr[2] = 30;
  39.     arr[3] = 40;
  40.     arr[4] = 50;
  41.  
  42.     printf("Original ");
  43.     displayList(arr, n);
  44.  
  45.     // Delete element at position 2 (0-based index)
  46.     deleteElement(arr, &n, 2);
  47.  
  48.     printf("After deletion ");
  49.     displayList(arr, n);
  50.  
  51.     return 0;
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement