问题虽然找到了 不过我不知道为什么,所以还请帮帮忙
原程序是这样的:
#include<malloc.h>
#include<stdio.h>
#define LEN sizeof(struct node_data)
//#define SIZE 4
struct node_data
{
int id;
char name[32];
struct node_data *next;
};
void delNode(struct node_data *header,int id)
{
struct node_data *p1,*p2;
if(header==NULL)
{
printf("\n list null!\n");
}
p1=header;
while(id!=p1->id&&p1->next!=NULL)
{
printf("id");
p2=p1;
p1=p1->next;
}
if(id==p1->id)
{
if(p1==header)
{
header=p1->next;
}
else
{
p2->next=p1->next;
}
free(p1);
}
}
void printNode(struct node_data *header)
{
struct node_data *p1;
p1=header;
if(header!=NULL)
{
do
{
printf("%d %s\n",p1->id,p1->name);
p1=p1->next;
}
while(p1!=NULL);
}
else
printf("the chain is null\n");
}
void insertNode(struct node_data *header, struct node_data *new_node)
{
struct node_data *p1;
p1=header;
if(new_node==NULL)
{
printf("The new node is null\n");
return;
}
if(header==NULL)
{
printf("xxx\n");
header=new_node;
printf("new addr of head is 0x%x\n", header);
}
else
{
while(p1->next!=NULL)
{
p1=p1->next;
}
p1->next=new_node;
}
new_node->next=NULL;
}
int main()
{
int del_id;
struct node_data *newNode, *p, *head;
FILE *fp;
char buf[128];
if((fp=fopen("sample.txt","r"))==NULL)
{
printf("cannot open file\n");
return -1;
}
head = NULL;
fgets(buf, 128, fp);
while(!feof(fp))
{
/* add your codes to insert node */
newNode = (struct node_data*)malloc(LEN);
sscanf(buf, "%d %s",&(newNode->id),newNode->name);
printf("addr of head is 0x%x\n", head);
if(head == NULL)
head = newNode;
else
insertNode(head, newNode);
printf("new addr of head is 0x%x\n", head);
fgets(buf, 128, fp);
}
printf("2id\n");
fclose(fp);
printNode(head);
printf("Input the deleted num is:");
scanf("%d", &del_id);
delNode(head, del_id);
printNode(head);
printf("Input the insertnode id and name:");
newNode = (struct node_data*)malloc(LEN);
scanf("%d%s",&(newNode->id),newNode->name);
insertNode(head, newNode);
printNode(head);
/* release all memory */
while(head != NULL)
{
p = head;
head = head->next;
free(p);
}
return 0;
}