XOR
XOR

Reputation: 23

Linked list code in C++

The following code for creating a linked list runs an infinite loop after entering the no. of numbers.

I thought a lot as to what the mistake might be but could not find a solution. Its maybe a small error that is going unnoticed. Please help!

CODE:

#include<iostream.h>
#include<conio.h>

struct Node {
    int data;
    Node* link;
};

Node* head;

void Insert(int x);
void Print();

void main()
{ 
    clrscr();
    head=NULL;
    cout<<"How many numbers";
    int n,x;
    cin>>n;

    for(int i=0; i<n; i++)
    {
        cout<<"enter no";
        cin>>x;
        Insert(x);
        Print();  
    }

}

void Insert (int x)
{
    Node* temp;
    temp= new Node();
    temp->data=x;
    temp->link=head;
    head=temp;
}

void Print()
{
    Node* temp=head;
    while(temp!=NULL)
    {
        cout<<"List is:"<<temp->data;
        temp=temp->link;
    }
    cout<<"\n";
}

Upvotes: 1

Views: 215

Answers (1)

Scott Deng
Scott Deng

Reputation: 119

It is not a right implementation of linked list. Every node should include a pointer to next one,not always the head. And the last node's pointer should be set to NULL. Insert function should contains two parameters, one for the data, and one for the linked list to pass in. When you traverse through the linked list, you should constantly check whether or not it is the end by checking whether the next pointer is NULL.

There are multiple way to implement a linked list, the more efficient way is to construct two struct. One for node, which include data and a pointer to the next, and one for linked list, which contains a pointer to the first and the last node. Every time you do a insertion, you insert to the end, and change the last pointer in linked list struct. Every time you start traverse, you start with first pointer.

By the way, you should really use the features provided by C++, like class and template to implement a linked list. C++ has even provides a good implementation of those sequential containers like linked list, dynamic array in standard template library. You should really try those new stuff, and use template and class to organize your code.

Upvotes: 4

Related Questions