【发布时间】:2014-04-08 09:12:27
【问题描述】:
我正在尝试创建一个链表以增强我的指针和地址概念。我必须通过以下方式创建链表:
(1) 在终端一次读取所有节点。
(2) 然后显示最后形成的最终链表。
我如何尝试这样做?
我首先阅读链表的大小(要输入的节点总数)。然后我在do-while 循环中一一读取所有节点。阅读所有节点后,我尝试创建链表。我区分了以下情况:节点是由count 变量创建的第一个节点,当该节点是第一个节点时,该变量将具有count=0,之后它将处于另一个循环中。
我得到的输出如下:
enter the size of node
4
start entering the number of elements until your size
2
3
4
5
Printing linked list
2-> //It don't print the other nodes, Just first one
hp@ubuntu:~/Desktop/pointer$
我这样做的完整代码是:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
struct node
{
int freq;
struct node * next;
};
typedef struct node node;
node * tree;
void main()
{
int size, data;
int count = 0; //this count flag is to check is it's first node or not inside the do-while loop.
tree = NULL;
printf("enter the size of node\n");
scanf("%d", & size);
printf("start entering the number of elements until your size\n");
node * temp3 = tree;
node * prev;
//Problem creating area is below
do
{
scanf("%d", & data);
if (count == 0)
{
node * temp;
temp = (node * ) malloc(sizeof(node));
temp-> freq = data;
temp-> next = NULL;
prev = temp;
}
else if (count != 0)
{
node * temp;
temp = (node * ) malloc(sizeof(node));
temp-> freq = data;
temp-> next = NULL;
prev-> next = temp;
}
size--;
++count;
}
while (size > 0);
printf("Printing linked list\n");
node * temp1;
temp1 = prev;
//there may be problem here
while (temp1-> next != NULL)
{
printf("%d-> ", temp1-> freq);
temp1 = temp1-> next;
}
printf("\n");
}
谁能帮我打印完整的链接列表,指出解决方案的错误?
【问题讨论】:
-
这里有几点注意事项:main 应该返回一些东西或设置为 void,据我计算,你有三个未使用的指针(tree、temp3 和 store),并且在你的 else if 中,你正在设置prev 节点到 temp,然后为 temp 分配内存并基本上覆盖它指向的内容。
-
调试器,调试器,调试器...
-
@JamesHostick 我在编辑中保留了 void main() 。但问题是如何避免这种节点的覆盖,因为我正在一起读取所有节点
-
我会说从将大量代码拆分为多个函数开始。
-
另外,最好不要使用 void main(),只使用 int main()。
标签: c algorithm data-structures linked-list singly-linked-list