高手给我看看这个 程序问题出在哪 谢谢了现
我的程序是用链表模拟lru算法的实现。
现在的 问题是 输入想用的数据,知可以实现一次
第二此输入数据的时候就出现断错误,可我始终找
不出哪错了。估计所指针和内存有错误。高手给
指点指点 ,谢谢了!
# include <stdio.h>
# include <stdlib.h>
# define LEN sizeof(struct student)
struct student
{
unsigned int num;
float score;
struct student * next;
};
struct student * creat(int n)
{
struct student *head;
struct student *p1;
struct student *p2;
int i;
printf( "in put num and score.\n ");
for (i = 0;i <n;i++)
{
p1 = (struct student *)malloc(LEN);
scanf( "%d,%f ",&p1-> num,&p1-> score);
if (i == 0)
{
head = p1;
p2 = p1;
}
else
{
p2-> next = p1;
p2 = p1;
p2-> next = NULL;
}
}
return head;
}
struct student * abc(struct student *head,struct student * stud)
{
struct student *p1;
struct student *p2;
struct student *p0;
p1 = NULL;
p2 = NULL;
p0 = stud;
p1 = head;
while((p0-> num != p1-> num) && (p1-> next != NULL))
{
p2 = p1;
p1 = p1-> next;
}
if (p0-> num == p1-> num)
{
if(p1-> next == NULL)
{
p0-> next = head;
head = p0;
p2-> next = NULL;
free(p1);
p1 = NULL;
}
else
{
p2-> next = p1-> next;
p0-> next = head;
head = p1;
free(p1);
p1 = NULL;
}
}
else
{
p0-> next = head;
head = p0;
p2-> next = NULL;
free(p1);
p1 = NULL;
}
return head;
}
print(struct student *head)
{
struct student *p;
printf( "Now,the list:\n ");
p = head;
if (head != NULL)
do
{
printf( "%d,%f\n ",p-> num,p-> score);
p = p-> next;
}while(p != NULL);
}
main()
{
struct student *head;
struct student *head2;
struct student *stu;
head = NULL;
head2 = NULL;
stu = NULL;
int n;
n = 10;
head = creat(n);
print(head);
printf( "in put the data you used:\n ");
stu = (struct student *)malloc(LEN);
scanf( "%d,%f ",&stu-> num,&stu-> score);
while(stu-> num != 0)
{
head2 = abc(head,stu);
print(head2);
printf( "in put the data you usde:\n ");
stu = (struct student *)malloc(LEN);
scanf( "%d,%f ",stu-> num,stu-> score);
}
}
[解决办法]
else
{
p2-> next = p1-> next;
p0-> next = head;
head = p1; //这里应该是head = p0;
free(p1);
p1 = NULL;
}
abc中有一个错误的地方。别的地方还没看完。