ronith
7/6/2018 - 2:34 PM

Delete a Linked List node at a given position

Given a singly linked list and a position, delete a linked list node at the given position.

Example:

Input: position = 1, Linked List = 8->2->3->1->7 Output: Linked List = 8->3->1->7

Input: position = 0, Linked List = 8->2->3->1->7 Output: Linked List = 2->3->1->7

// https://www.geeksforgeeks.org/delete-a-linked-list-node-at-a-given-position/
#include <iostream>
#include <list>
using namespace std;

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

void print(node* n) {
    while (n != NULL) {
        cout<< n->data << " ->";
        n = n->next;
    }
    return;
}

node* insert(node* head, int n) {
    node* list = (node*)malloc(sizeof(node*));
    list->data = n;
    list->next = head;
    head = list;
    return head;
}

node* del(node* head, int n) {
    node* list = head;
    if (n==0){
        head = list->next;
        return head;
    }
    node* prev = list;
    while (list != NULL && n>0) {
        prev = list;
        list = list->next;
        n--;
    }
    prev->next = list->next;
    return head;
}

int main() {
    int n;
    node* head = NULL;
    while(true) {
        cout<< "Enter the elements, and -999 to stop: ";
        cin>>n;
        if (n == -9)
            break;
        else
            head=insert(head,n);
    }
    cout<< "Intial List: \n";
    print(head);
    cout<< "Index to be deleted: ";
    cin>>n;
    head=del(head,n);
    cout<< "Final List: \n";
    print(head);
}