|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
//这是C链表,是建立和删除链表的程序,输入num(学号)和score,问一下当删除某节点,怎么使得学号按顺序输出?
/******************************************
**************这是一个C链表程序***********/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct student
{
int num;
int score;
struct student *next;
};
void main ()
{
struct student *creat(struct student *head);//链表函数!
void print(struct student *head);//打印函数!
struct student *del(struct student *head,int num);//删除函数!
int n;
struct student *head;
head=NULL;
head=creat(head);
print(head);
printf("Please input the num you will delete: ");
scanf("%d",&n);
print(del(head,n));
printf("\n");
}
int n=0;
struct student *creat(struct student *head)
{
struct student *p1,*p2;
p1=p2=(struct student *)malloc(sizeof(struct student));
printf("Please input the num: ");
scanf("%d",&p1->num);
printf("Please input the score: ");
scanf("%d",&p1->score);
p1->next=NULL;
while(p1->num!=0)
{ n++;
if(head==NULL)
{
head=p1;
}
else
{
p2->next=p1;
}
p2=p1;
p1=(struct student *)malloc(sizeof(struct student));
printf("Please input the num: ");
scanf("%d",&p1->num);
printf("Please input the score: ");
scanf("%d",&p1->score);
}
p2->next=NULL;
return head;
}
void print(struct student *head)
{
struct student *temp;
temp=head;
printf("the all record is %d\n",n);
while(temp!=NULL)
{
printf("%d %d\n",temp->num,temp->score);
temp=temp->next;
}
}
struct student *del(struct student *head,int num)
{
struct student *p1,*p2;
if(head==NULL)
{
printf("The list is a null!");
goto END;
}
p1=head;
while(p1->num!=num&&p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(p1->num==num)
{
if(head->num==num)
{
/*struct student *temp;
temp=head;*/
head=head->next; //类似于这里一样,但是下面想不出
/*head->num=temp->num;*/
}
else
{
p2->next=p1->next; //这里该怎么定义,试着学号是按顺序排列的呢?
}
printf("The num you enter has been deleted!success!\n");
n--;
}
else
{
printf("The num you enter is not in!\n");
}
END:
return head;
}
|
|