ronith
7/6/2018 - 11:47 AM

Linked List | Set 2 (Inserting a node)

// https://www.geeksforgeeks.org/linked-list-set-2-inserting-a-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 push(int n) {
    node* list= (node*)malloc(sizeof(node*));
    list->data=n;
    list->next=head;
    head=list;
}

void append(int n) {
    node* list= (node*)malloc(sizeof(node*));
    list->data = n;
    list->next = NULL;
    node* last= (node*)malloc(sizeof(node*));
    last=head;
    while (last->next != NULL )
        last = last->next;
    last->next = list;
}

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

int main() {
    int n,i;
    head = NULL;
    cout<< "Enter 1 to push at front and 2 to append at last \n";
    while(true) {
        cout<< "Enter the elements, and -999 to stop: ";
        cin>>n>>i;
        if (n==-999)
            break;
        if (i==1)
            push(n);
        if (i==2)
            append(n);
    }
    print();
}