Linked list class 3: Optimal input o(n)

 // Online C++ compiler to run C++ program online

#include <iostream>

using namespace std;


struct node{

    public:

    int data;

    node* next;

    

    node(int data){

        this->data=data;

        next=NULL;

    }

};


void display(node* head){

    node* temp=head;

    while(temp!=NULL){

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

        temp=temp->next;

    }

    

    

    

}


node* input_optimal(){

    int data;

    cin>>data;

    node* head=NULL;

    node*tail=NULL;

    while(data!=-1){

        node*n=new node(data);

        if (head==NULL){

        head=n;

        tail=n;

        }

        else{

            tail->next=n;

            //tail=tail->next;

            //OR

            tail=n;

            

        }

        cin>>data;

    }

    return head;

}

int main() {

    node*head=input_optimal();

    

    

    

    display(head);

    

    

    

    


    return 0;

}

Comments

Popular posts from this blog

Sum of Even Numbers till N

Find the Runner-Up Score!

Print All Substrings