链表逆置为什么错了?急!

来源:百度知道 编辑:UC知道 时间:2024/05/17 02:57:25
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
#define NULL 0
#define LEN sizeof(struct student)
typedef struct student
{
int score;
struct student *next;
}stulist;
int n;
stulist * Creat(void)//*******************录入
{
stulist *head;
stulist *p1,*p2;
p1=(stulist*)malloc(LEN);
p2=(stulist*)malloc(LEN);
head=NULL;
n=0;
puts("Please input the node:");
scanf("%d",&p1->score);
while(p1->score!=0)
{
n++;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(stulist*)malloc(LEN);
scanf("%d",&p1->score);
}
free(p1);
p1=NULL;
p2->next=NULL;
return head;
}
void Print(stulist * head)//******************打印显示
{
stulist * p;
p=head;
printf("目前有 %d 项记录。\n"

首先,p1=p2->next;是把p2的后面一个结点的地址给了p1;然后你又p1=p2;把p2的地址给了p1,这样不是等于前面那一句没有用了。然后p2移动到下一个结点。
这样循环下去,只是等于不断的把链表的每个节点都赋给p1,没有实质性的操作。最后只是把最后一个结点给了p1而已。不知道说的情不清楚?
建议你还不熟悉链表的操作的时候,最好就画个图,边看边写操作。#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
#define NULL 0
#define LEN sizeof(struct student)

typedef struct student
{
int score;
struct student *next;
}stulist;

int n;
stulist * Creat(void)//*******************录入
{
stulist *head;
stulist *p1,*p2;
p1=(stulist*)malloc(LEN);
n=0;
puts("Please input the node:");
scanf("%d",&p1->score);
p1->next=NULL;
while(p1->score!=0)
{
n++;
if(n==1)
p2=p1;
else
p1->next=p2; //p1指向p2
p2=p1;
//相当于把p1插入到p2的头
p1=(stulist*)malloc(LEN);
scanf("%d",&p1->score);
}