Monday, November 22, 2021

Deleting node from given position

 #include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};

void push(struct node** head_ref, int new_data)
{
    struct node* new_node = (struct node*) malloc(sizeof(struct node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}

void show(struct node* sho) {
    while(sho!=NULL){
        printf("%d", sho->data);
        sho = sho->next;
    }
    printf("Reached");
}
void deleteNode(struct node **head, int position) {
    struct node* current = *head;
    struct node* previous;
    struct node* temp;
    if(*head == NULL){
        printf("List is Empty");
    } else if(position == 1) {
        temp = *head;
        *head = (*head)->next;
        free(temp);
        temp = NULL;
    } else {
        int i;
        for(i = 1; i<=(position - 1); i++) {
            previous = current;
            current = current->next;
        }
        temp = current;
        previous->next = current->next;
        free(temp);
        temp = NULL;
    }
       
}
int main()
{
    struct node* head = NULL;
    push(&head, 4);
    push(&head, 3);
    push(&head, 2);
    push(&head, 1);
    show(head);
    deleteNode(&head, 1);
    show(head);
    return 0;
}

No comments:

Post a Comment

Priority queue deleting elements after ascending inputs Gaand Fadd

 using namespace std; #include<iostream> #define N 5 class pq { public:     int* arr;     int front;     int rear;     pq() {         ...