ronith
7/6/2018 - 11:48 AM

Linked List | Set 3 (Deleting a node)

// https://www.geeksforgeeks.org/linked-list-set-3-deleting-node/
#include <iostream>
#include <list>
using namespace std;

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

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

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

void del (int n) {
    node* list = head;
    while (list != NULL && list->data == n) { // if head has the value, we delete it.
        head = list->next;
        list=list->next;
    }

    node* prev = head;
    list=list->next;
    while (list != NULL) {
        if (list->data == n) {
            prev->next = list->next;
            list=list->next;
        }
        else {
            prev = list;
            list = list->next;
        }
    }
    free(list);
}

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