Printing a simple linked list in C++, data-structure

154 Views Asked by At

I have problems printing a singly linked list,it must look for example so: [1:2][3:4][7:2][9:1], but the result/the output is without the last element, i.e. so: [1:2][3:4][7:2]. This is my data-structure:

struct numbers {
int info1;
int info2;   
numbers *next; 
};

struct numbers* next= NULL; //At first 0,because the list is empty
struct numbers* head=NULL;  //at the beginning

And the function,that I call later:

void printing(numbers *head) { 
numbers *temp=head;
if(head!=NULL) {
    do {
        printf("[%d:%d]",temp->info1, temp->info2);
        temp=temp->next;
    }   while(temp->next!=head && temp->next!=0);
}   
    return;
}

Is there a mistake in this function?

4

There are 4 best solutions below

0
On BEST ANSWER

I do not understand the condition

temp->next!=head

The last node is not outputed because instead of

temp->next!=0

you have to check

temp != 0

because you already moved the pointer inside the loop

temp=temp->next;

So the function is wrong. It should look like

void printing( numbers *head ) 
{ 
    for ( numbers *temp = head; temp != 0; temp = temp->next )
    {
        printf( "[%d:%d]", temp->info1, temp->info2 );
    }
}
1
On

Just this code is enough . The problem with your code is that you return when ever it's next pointer become NULL , that's the case for last node .

void printing(numbers *head) { 
  numbers *temp=head;
  while( temp != NULL ){
        printf("[%d:%d]",temp->info1, temp->info2);
        temp=temp->next;
  }   
}
0
On

The problem is you are advancing to the next node and then you are checking if that node has an empty next node. Because of this you will never print the last node. You can rewrite your code to:

void printing(numbers *head) {
    numbers *temp = head;
    if (head != NULL) {
        while (temp != NULL)
            printf("[%d:%d]", temp->info1, temp->info2);
            temp = temp->next;
        }
    }
    return;
}
0
On

In the while condition, I don't know why you are checking for temp->next!=head.

But for null condition, you should be checking temp!=0 or temp!=NULL instead of temp->next!=0