#include<stdio.h>
#include<stdlib.h>
typedef struct student
{
int score;
struct student *next;
}Linklist;
Linklist *creat(int n);
void newprintf(Linklist *head);
void Pfree(Linklist *head);
int main()
{
int n=2;
Linklist *head;
head=creat(n);
newprintf(head);
Pfree(head);
return 0;
}
Linklist *creat(int n)
{
Linklist *head,*node,*end;
head=(Linklist *)malloc(sizeof(Linklist));
end=head;
for(int i=0;i<n;i++)
{
node=(Linklist *)malloc(sizeof(Linklist));
scanf("%d",&head->score);
end->next=node;
end=node;
}
end->next=NULL;
return head;
}
void newprintf(Linklist *head)
{
Linklist *p;
p=head;
if(p==NULL)
{
printf("此链表为空\n");
return;
}
while(p->next!=NULL)
{
p=p->next;
printf("我是%d\n",p->score);
}
}
void Pfree(Linklist *head)
{
Linklist *p;
p=head;
while(p!=NULL)
{
p=head->next;
free(head);
head=p;
}
}
输出结果和理想中的不一样(那个n是长度,head是头结点)
你这create明显就多创建了一个节点啊。head指向第一个节点,不是单独一个节点
给改了一下:
#include<stdio.h>
#include<stdlib.h>
typedef struct student
{
int score;
struct student *next;
}Linklist;
Linklist *creat(int n);
void newprintf(Linklist *head);
void Pfree(Linklist *head);
int main()
{
int n=2;
Linklist *head;
head=creat(n);
newprintf(head);
Pfree(head);
system("pause");
return 0;
}
Linklist *creat(int n)
{
Linklist *head = NULL,*node,*p;
for(int i=0;i<n;i++)
{
node=(Linklist *)malloc(sizeof(Linklist));
scanf("%d",&node->score);
node->next = NULL;
if(head == NULL)
{
head = node;
head->next = NULL;
p = head;
}
else
{
p->next = node;
p = node;
}
}
return head;
}
void newprintf(Linklist *head)
{
Linklist *p = head;
if(p==NULL)
{
printf("此链表为空\n");
return;
}
while(p!=NULL)
{
printf("我是%d\n",p->score);
p=p->next;
}
}
void Pfree(Linklist *head)
{
Linklist *p = head;
while(p!=NULL)
{
p=head->next;
free(head);
head=p;
}
}