编程,是与计算机的关系。你必须想让它发挥作用,否则你会放弃;你需要了解她的想法,否则你将无法沟通;最重要的是,你应该清楚你不想要什么,否则你将永远无法要求它,更不用说对整个事情的进展感到满意了。
学习新算法时,您应该做的第一件事就是尝试在纸上解决它。绘制代表您的数据结构的框:排列在数组中的框和由 malloc 返回的自由浮动框。写出所有变量的值。然后一步一步地按照你的算法,用值填充框,为你的指针绘制箭头等。这可能看起来像一个拖累,但是当你遇到非常奇怪的错误时,这样做会更加痛苦。
我将在您的代码中添加注释(算法本身似乎有几个问题,而不仅仅是一个错误)在您调试问题并发现更多错误时继续编辑您的问题中的代码。我会帮忙的。
我发现了两个错误:您的 add 函数总是将列表减少到两个元素。您的代码可以保证在某个时候出现段错误,因为您没有将最后一个指针设置为 NULL,因此您不会知道列表的末尾在哪里。
您的代码的最大问题是它尝试太多。您不知道如何实现链接列表,而您已经直接开始实现链接列表数组。去痛苦的最快方式。软件开发中一次迈出一步的技术术语是“单元测试”。谷歌它,看看人们对它的重要性有多狂热。:P
祝你好运!
struct node{
int x;
struct node *link;
};
add(struct node *arrayy[],int value) //arrayy is a array of pointers.
{
struct node *nodey = (struct node *)malloc(sizeof(struct node));
nodey->x=value;// nodey will be at the end of the list, but nodey->link contains some garbage value. how will you know that this is the last element the next time you traverse the list.
if(arrayy[value]==NULL) // do you actually want the "value'th" element of the array or something else?
//is value the position or the contents?
{
printf("I am not pointing to something...now I am hehehe\n");
arrayy[value]=nodey;
}
else
{
printf("I already have a head..now my link is pointing at something\n");
while(arrayy[value])
{
if(arrayy[value]->link==NULL)
{
arrayy[value]->link=nodey;
break;
}
arrayy[value]=arrayy[value]->link;//you are replacing arrayy[value] with the next element in the array. the malloced structs that was originally pointed to by arrayy[value] now has no pointer pointing to it, so there is no way to access those nodes. maybe you want a separate variable current node that you can modify without affecting the original link list : current_node=current_node->link ? Also, since you are "deleting" all the elements bu the last one before adding the new node, your list will never be more than 2 elements long
}
}
}
print(struct node *arrayy[])
{
int x= 0;
for(x; x<10; x++)
{
while(arrayy[x])
{
printf("%d",arrayy[x]->x);
arrayy[x]=arrayy[x]->link; //again, you are modifying the array as you read it.
}
}
}
main(void)
{
struct node *array[10]={NULL}; //you will have array of 10 pointers, each pointing to address 0. does this mean that you wnt 10 seperate lists?
add(array,1);
add(array,1);//debug by putting different values in different nodes
add(array,1);
printf("%d",array[1]->link->link->x);
}