Take Input Linked Lists

 #include <iostream>

#include <cstddef>

using namespace std;


class node{

    public:

    int data;

    node*next;

    

    node(int data){

        this -> data=data;

        next=NULL;

    }

};

node*takeinput(){

    int data;

    cin>>data;

    node*head=NULL;

    while(data!=-1){

        node*newnode=new node(data);

        if(head==NULL){

            head=newnode;

        }

        else {

            node*temp=head;

            while(temp->next!=NULL){

                temp=temp->next;

            }

            temp->next=newnode;

        }

        cin>>data;

    }

    return head;

}

void print(node *head){

    node*temp=head;//use on temp var

    while(temp!=NULL){

        cout<<temp->data<<" ";

        temp=temp->next;

    }

    /*temp=head;//use on temp var

    while(temp!=NULL){

        cout<<temp->data<<" ";

        temp=temp->next;

    }*/

}

int main() {

    

    node*head=takeinput();

    print(head);

    //linked list of 5 elements

    /*

    node n1(1);

    node*head=&n1;

    node n2(2);

    n1.next=&n2;

    node n3(3);

    

    node n4(4);

    node n5(5);

    n2.next=&n3;

    n3.next=&n4;

    n4.next=&n5;

    //print(head);

    takeinput();

    

    //n5.next=&n2;

    

   /* node n1(1);

    //node*head=&n1;//define head

    node n2(2);

    n1.next=&n2;

   // cout<<head->data;

    //Dynamic

    /*

    node*n3=new node(10);

    node*head=n3;

    node*n4=new node(20);

    n3->next=n4;

    cout<<head->data;*/

    

    

    

    return 0;

}

Comments

Popular posts from this blog

Sum of Even Numbers till N

Find the Runner-Up Score!

Print All Substrings