在一个有序(按非递减顺序)的链表中插入一个元素为x的结点,使插入后的链表仍然有序(链表数据域为整型数,N为6)。
**输入提示:"输入数组6个元素的值。\n"
**输入格式:"%d"
**输出提示:"此链表各个结点的数据域为:"
**输出格式:"%d " (注:所有数据输出结束后有一个回车)
**输入提示:"输入要插入的数据x:"
**输入格式:"%d"
**输出提示:"插入后链表各个结点的数据域为:"
**输出格式:"%d " (注:所有数据输出结束后有一个回车)
程序运行示例如下:
输入数组6个元素的值。↙
12 23 34 45 56 67
此链表各个结点的数据域为:12 23 34 45 56 67 ↙
输入要插入的数据x:36
插入后链表各个结点的数据域为:12 23 34 36 45 56 67↙
#include<stdio.h>
#include<stdlib.h>
struct num {
int a;
struct num * next;
};
struct num* Create(void){
struct num*ph,*p,*pr;
ph=(struct num*)malloc(sizeof(struct num));
pr=ph;
pr->next=NULL;
int count =0,n;
do{
scanf("%d",&n);
if(count!=6){
count ++;
p=(struct num*)malloc(sizeof(struct num));
p->a=n;
p->next=NULL;
pr->next=p;
pr=p;
}
}while(count !=6);
return ph;
}
void Traverse(struct num* ph){
struct num*p;
p=ph->next;
while(p!=NULL){
printf("%d ",p->a);
p=p->next;
}
}
void Add(struct num *ph,int x){
struct num*pr,*p;
pr=ph;
while(pr->next->a<x){
pr=pr->next;
}
p=(struct num*)malloc(sizeof(struct num));
if(p==NULL){
return;
}
p->a=x;
p->next=pr->next;
pr->next=p;
}
int main(){
printf("输入数组6个元素的值。\n");
struct num* head=Create();
printf("此链表各个结点的数据域为:");
Traverse(head);
printf("\n");
printf("输入要插入的数据x:");
int x;
scanf("%d",&x);
Add(head,x);
printf("插入后链表各个结点的数据域为:");
Traverse(head);
}