文章目录
1.建立一个单向有序链表,初始包含1 5 7 16输入一个1~20的数,将其插入其中并使链表依然有序
扩展:输入n个数,使其依然有序。
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}Node;
Node *create()
{
Node *head,*r,*p;
head=(Node *)malloc(sizeof(Node));
head->next =NULL;
r=head;
printf("初始化链表,请输入4个数字:");
for(int i=1;i<=4;i++)
{
int x;
scanf("%d",&x);
p=(Node *)malloc(sizeof(Node));
p->data =x;
r->next =p;
r=p;
}
r->next =NULL;
return head;
}
Node *insert(int n)
{
Node *head,*pre,*p;
head=create();
pre=head;
int x,i;
printf("输入你要插入的数字:");
for(i=1;i<=n;i++)
{
scanf("%d",&x);
p=(Node *)malloc(sizeof(Node));
p->data =x;
pre=head->next ;
if(pre->data >=x)
{
p->next =head->next ;
head->next =p;
}
else
while(pre->next )
{
if(pre->data <x&&pre->next ->data>=x)
{
p->next =pre->next ;
pre->next =p;
break;
}
else
pre=pre->next ;
}
if(pre->next ==NULL)
{
pre->next =p;
p->next =NULL;
}
pre=head->next ;;
}
return head;
}
int main(void)
{
Node *head;
int n;
printf("请输入要插入多少个数字:");
scanf("%d",&n);
head=insert(n);
head=head->next ;
printf("插入后的链表结果:");
while(head)
{
printf("%d ",head->data );
head=head->next ;
}
}
运行结果
请输入要插入多少个数字:5
初始化链表,请输入4个数字:1 5 9 16
输入你要插入的数字:-5 -1 4 0 17
插入后的链表结果:-5 -1 0 1 4 5 9 16 17
--------------------------------
Process exited after 24.78 seconds with return value 0
请按任意键继续. . .
2反转一个单链表。
示例:
输入: 1 2 3 4 5
输出: 5 4 3 2 1