#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct student
{
int no;
double score;
struct student *next;
};
//正向建立链表
struct student *create()
{
int num;
struct student *head,*p1,*p2;
head=NULL;
p2=NULL;
printf("输入数据直到0停止\n");
scanf("%d",&num);
while(num!=0)
{
p1=(struct student *)malloc(
sizeof(struct student));
p1->no=num;
p1->next=NULL;
if(head==NULL) head=p1;
else p2->next=p1;
p2=p1;
scanf("%d",&num);
}
return head;
}
//打印链表
void print(struct student *head)
{
struct student *p;
p=head;
while(p!=NULL)
{
printf("%5d ",p->no);
p=p->next;
}
printf("\n");
}
//反向建立链表
struct student *rcreate()
{
struct student *head,*p;
int num;
head=NULL;
printf("输入数据直到0停止\n");
scanf("%d",&num);
while(num!=0)
{
p=(struct student *)malloc(
sizeof(struct student));
p->no=num;
p->next=head;
head=p;
scanf("%d",&num);
}
return head;
}
//删除节点
struct student *del(struct student
*head,int num)
{
struct student *p1,*p2;
if(head==NULL) printf("NULL\n");
else
{
p1=head;
while(p1->no!=num&&p1->next
!=NULL)
{
p2=p1;
p1=p1->next;
}
if(p1->no==num)
{
if(p1==head) head=head
->next;
else p2->next=p1->next;
free(p1);
printf("删除成功\n");
}
else
printf("没有找到\n");
}
return head;
}
//插入新节点(按升序
struct student *insert(struct student
*head,int no)
{
struct student *p1,*p2,*q;
q=(struct student *)malloc(
sizeof(struct student));
q->no=no;
q->next=NULL;
if(head==NULL) head=q;
else
{
p1=head;
while(no>p1->no&&p1->next
!=NULL)
{
p2=p1;
p1=p1->next;
}
if(no<=p1->no)
{
if(p1==head)
{
q->next=head;
head=q;
}
else
{
p2->next=q;
q->next=p1;
}
}
else
p1->next=q;
}
return head;
}
//链表的反向
struct student *reverse(struct student
*head)
{
struct student *head1,*p=head;
head1=NULL;
while(p!=NULL)
{
head=head->next;
p->next=head1;
head1=p;
p=head;
}
return head1;
}
//链表的合并(没有循序
struct student *comlist(struct
student *head,struct student *head1)
{
struct student *p;
if(head==NULL) head=head1;
else
{
p=head;
while(p->next!=NULL) p=p->next;
p->next=head1;
}
return head;
}
//链表的排序
struct student *sort(struct student
*head)
{
struct student *p,*head1;
head1=NULL;
p=head;
while(p!=NULL)
{
head1=insert(head1,p->no);
p=p->next;
}
return head1;
}
int main()
{
struct student *head,*head1;
int i,num;
while(1)
{
printf("1.创建链表\n");
printf("2.反向创建链表\n");
printf("3.打印链表\n");
printf("4.插入节点\n");
printf("5.删除节点\n");
printf("6.反转链表\n");
printf("7.合并两个链表\n");
printf("8.排序链表\n");
printf("9.退出\n");
scanf("%d",&i);
switch(i)
{
case 1:
head=create();
print(head);
break;
case 2:
head1=rcreate();
print(head1);
break;
case 3:
print(head);
break;
case 4:
printf("插入数据是:\n");
scanf("%d",&num);
head=insert(head,num);
print(head);
break;
case 5:
printf("删除数据是:\n");
scanf("%d",&num);
head=del(head,num);
print(head);
break;
case 6:
head=reverse(head);
print(head);
break;
case 7:
head=comlist(head,head1);
print(head);
break;
case 8:
head=sort(head);
print(head);
break;
case 9:
exit(0);
default:
printf("输入错误\n");
}
}
return 0;
}
动态链表的构建
最新推荐文章于 2024-09-12 15:24:39 发布