简体   繁体   English

用C ++数据结构打印一个简单的链表

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

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, ie so: [1:2][3:4][7:2]. 我在打印单链列表时遇到问题,它必须看起来像这样:[1:2] [3:4] [7:2] [9:1],但是结果/输出没有最后一个元素,即因此:[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? 这个功能有错误吗?

In the while condition, I don't know why you are checking for temp->next!=head . while条件下,我不知道您为什么要检查temp->next!=head

But for null condition, you should be checking temp!=0 or temp!=NULL instead of temp->next!=0 但是对于空条件,您应该检查temp!=0temp!=NULL而不是temp->next!=0

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 );
    }
}

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 . 代码的问题在于,当下一个指针变为NULL时,您将返回,最后一个节点就是这种情况。

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

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM