【发布时间】:2014-08-05 19:44:27
【问题描述】:
我用 C 语言编写了一个链表的实现(有两个点,一个用于下一个值,一个用于上一个值),我正在尝试测试我的代码。
我检查了它是否正确扫描和打印,但是,当我尝试测试我编写的代码以在列表中查找值时,它返回不正确的输出。
在列表中查找的代码是:
node* find_in_list(node *anchor,data_type x)
{
node *temp;
int is_empty=0;
is_empty=is_list_empty(anchor);
if(is_empty)
return NULL;
temp=anchor->next;
while(temp!=NULL)
{
if(temp->data==x)
return temp;
temp=temp->next;
}
return temp;
}
检查列表是否为空的代码是
int is_list_empty(node *anchor)
{
int boolean=0;
if(anchor->next=NULL)
boolean=1;
return boolean;
}
需要注意的是,锚永远不会改变。我将锚定义为链表中没有实际值的节点,而是将其用作指向第一个“真实”节点的指针。
虚空主要是
#include "linked_list.h"
void main()
{
data_type num;
node *anchor;
anchor=create_node();
scan_list(anchor);
printf("The list scanned is \n");
print_list(anchor);
printf("Enter the number you wish to find\n");
scanf("%d",&num);
printf("The address of %d is\n",num);
printf("%p",find_in_list(anchor,num));
getch();
}
扫描和打印已正确完成。它确实打印了正确的列表,但是当我尝试打印列表中某个值的地址时(无论我输入什么值),它都会返回 000000。
有什么问题?
【问题讨论】:
-
if(anchor->next=NULL)错误。 -
谢谢...我永远不会发现一个 :P 它现在按预期工作。
-
为什么是
int is_empty=0; is_empty=is_list_empty(anchor); if(is_empty) return NULL;?为什么不if (is_list_empty(anchor)) return NULL;? -
您应该启用所有警告(例如,如果使用
gcc -Wall -g编译,则使用 GCC....) -
问题是我写了“=”而不是“==”。考虑关闭 :) 还修复了 Jashaszun 建议的 is_empty 问题
标签: c list pointers printing linked-list