S L
S L

Reputation: 14318

Printing the elements two linked list behaving weird

I wrote a linked list with following code. The first print is working, but second print is not.

int main() {
    Node *A, *B;


    B = InsertTail(B, 2);
    B = InsertTail(B, 3);
    B = InsertTail(B, 8);
    B = InsertTail(B, 10);

    Print(B);

    A = InsertTail(A, 1);
    A = InsertTail(A, 5);
    A = InsertTail(A, 10);
    A = InsertTail(A, 12);
    A = InsertTail(A, 16);

    Print(A);

    return 0;
}

Function InsertTail inserts data in second argument to the end of the list and returns the head of the list. And Print function prints the list if all elements.

Print function is implemented as

void Print(Node *head)
{
    Node *current = head;
    if(head == NULL){ return; }
    while(current != NULL){
        cout << current->data << endl;
        current = current->next;
    }
}

And, InsertTail is implemented as

Node* InsertTail(Node *head,int data)
{
    Node *current = new Node, *temp = head;
    current->data = data;
    current->next = NULL;

    if(temp==NULL){return current;}
    else{
        while(temp->next != NULL){ temp=temp->next;}
        temp->next = current;
    }
    return head;
}

I tried to debug it, the first value of A is fine but on second value, there is data = 1836017711. Here is a screenshot. enter image description here

Upvotes: 0

Views: 46

Answers (2)

Petr
Petr

Reputation: 9997

You do not seem to initialize neither A neither B before the calls. Judging by your Print function, I suppose that A and B should be initialized with NULL:

Node *A=NULL, *B=NULL;

Without initialization, I guess this is undefined behavior, anything can happen. In simplest case, A and B just happen to point to a random place in memory with random contents (and you are very lucky to have even B work).

P.S. Why do you insert at tail, but keep a pointer to head only? I suggest you keep a pointer to tail too so that you do not go along all list each time.

Upvotes: 1

Ivan Mushketyk
Ivan Mushketyk

Reputation: 8285

You should initialize your lists with NULL, while you are initializing them with garbage:

Node *A, *B;

It should be

Node *A=NULL, *B=NULL;

Upvotes: 1

Related Questions