#include<stdio.h>
#include<malloc.h>
typedef struct node_t {
int i;
struct node_t* link;
} node;
node* head = NULL;
int main() {
int i = 10;
node* temp = NULL;
head = (node *)malloc(sizeof(node));
temp = (node *)malloc(sizeof(node));
if(temp == NULL) {
printf("\n malloc for temp node failed! \n");
}
else {
/* linked list logic to add the elements in the beginning */
while(i<=10) {
temp->i = i;
temp->link = NULL;
if(head == NULL) {
head = temp;
}
else {
temp->link = head;
head = temp;
}
i++;
}
}
for(temp = head; temp->link != NULL; temp = temp->link) {
printf("\n The data is:%d \n",temp->i);
}
free(temp);
free(head);
return 0;
}
我正在尝试一个简单的链表程序。我没有得到输出。
最佳答案
1) 每次为 tmp
赋值时,都必须分配节点 (tmp
)。并且不只分配一次tmp
。请参阅以下固定代码以了解如何操作
2) 下面的for
循环是错误的:
for(temp = head; temp->link != NULL; temp = temp->link) {
此 for
循环已在以下代码中修复
3) 对于free
,您必须浏览整个链表,然后释放每个节点。请参阅以下固定代码。
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node_t{
int i;
struct node_t* link;
}node;
node* head = NULL;
int main(){
int i = 1;
node* temp = NULL;
/* linked list logic to add the elements in the beginning */
while(i<=10){
temp = (node *)malloc(sizeof(node));
if(temp == NULL){
printf("\n malloc for temp node failed! \n");
exit(1);
}
temp->i = i;
temp->link = NULL;
if(head == NULL){
head = temp;
}
else{
temp->link = head;
head = temp;
}
i++;
}
for(temp = head; temp != NULL; temp = temp->link){
printf("\n The data is:%d \n",temp->i);
}
while (head!=NULL)
{
temp = head->link;
free(head);
head = temp;
}
}
关于c - C中没有程序输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13621062/