#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
struct node_data
{
int id;
char name[20];
struct node_data *next;
};
#define LEN sizeof(struct node_data)
struct node_data *delNode(struct node_data *header,int id)
{
struct node_data *p1,*p2;
p1=header;
while(id!=p1->id&&p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
p2->next=p1->next;
free(p1);
return header;
}
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);
}
*/
while(p1->next!=NULL)
{
p1=p1->next;
}
p1->next=new_node;
new_node->next=NULL;
}
int main()
{
int del_id,flag=0;
struct node_data *newNode, *p, *head;
FILE *fp;
char buf[128];
if((fp=fopen("d:\\2.txt","r"))==NULL)
{
printf("cannot open file\n");
return -1;
}
head = NULL;
fgets(buf, 128, fp);
while(!feof(fp)||flag<2)
{
/* add your codes to insert node */
newNode = (struct node_data*)malloc(LEN);
sscanf(buf, "%d %s",&(newNode->id),newNode->name);
printf("addr of node is 0x%x\n", newNode);
if(head == NULL)
{
head=newNode; /*问题出在没有把head->next赋为NULL*/
head->next=NULL;
}
else
{
insertNode(head, newNode);
}
printf("new addr of node is 0x%x\n", newNode);
fgets(buf, 128, fp);
if(feof(fp))
flag++;
}
fclose(fp);
printNode(head);
printf("Input the deleted num is:");
p=head;
scanf("%d", &del_id);
if(p->id==del_id)
{
head=p->next;
}
else
{
head=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);
}
getch();
return 0;
}
上面的程序已经改好了,在windows系统运行是没问题的,至于linux我没,
楼主您再看看吧,问题已经注明了.您在新建节点的时候头节点另外新建,却没有把它的next成员指向null.
还有一个问题是访问文件的时候出的问题,按照您的原程序,文件最后一行不能被存到链表中去,也改了,您再看看吧,
对不礼貌的女生收钱......