【发布时间】:2017-06-28 19:48:41
【问题描述】:
我编译代码时没有错误,但是两次输入后程序在运行时崩溃。也许有一些我无法弄清楚的逻辑错误。我试图在链表的尾部插入节点,同时只保持头部位置。
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
};
struct Node *head;
//print the element of the lists
void print(){
printf("\nThe list from head to tail is as follows \n");
struct Node* temp = head;
while(temp!=NULL){
printf("\n %d ",(*temp).data);
temp = (*temp).next;
}
}
//insert a node at the tail of the linked list
void insert_at_tail(int data){
struct Node* temp = head;
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data=data;
new_node->next=NULL;
if(temp==NULL){
head=new_node;
}
else{
while(temp!=NULL){temp=temp->next;}
(*temp).next=new_node;
}
}
int main(){
head = NULL;
int i,data;
for(i=0;i<5;i++){
scanf("%d",&data);
insert_at_tail(data);
}
print();
return 0;
}
【问题讨论】:
-
为了便于阅读和理解:: 1) 单独的代码块(for、if、else、while、do...while、switch、case、default)通过一个空行 2) 跟随公理:每行只有一个语句,并且(最多)每个语句一个变量声明。
-
在调用
scanf()时,一定要检查返回值(不是参数值),确保操作成功。 -
在调用任何堆分配函数(malloc、calloc、realloc)时,1) 始终检查 (!=NULL) 返回值以确保操作成功。 2) 返回类型为
void*,因此可以分配给任何指针。强制转换只会使代码混乱,使其更难以理解、调试等。
标签: c pointers data-structures linked-list singly-linked-list