#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct node //定义结点
{
int data;
struct node *next;
}LNode;
void print(LNode *h); //打印函数
void insert(LNode *h); //插入函数
void change(LNode *h); //逆置函数
LNode *create(); //创建函数
void hebing(LNode *h,LNode *m,LNode *c); //合并函数
int main(){
LNode *h,*m,*c;
int i;
printf("**********************************\n"); //主菜单
printf(" 请选择要进入的系统\n");
printf(" 1.创建一个单链表\n");
printf(" 2.打印单链表\n");
printf(" 3.插入一个数据\n");
printf(" 4.将单链表逆置\n");
printf(" 5.两个升序单链表合并\n");
printf(" 6.退出系统\n");
printf("\n");
while(1){
scanf("%d",&i);
switch(i){ //选择菜单
case 1:
h=create();break;
case 2:
print(h);break;
case 3:
insert(h);break;
case 4:
change(h);break;
case 5:
m=create();
hebing(h,m,c);
break;
case 6: return 0;
}
printf("**********************************\n");
printf(" 请选择要进入的系统\n");
printf(" 1.创建一个单链表\n");
printf(" 2.打印单链表\n");
printf(" 3.插入一个数据\n");
printf(" 4.将单链表逆置\n");
printf(" 5.两个升序单链表合并\n");
printf(" 6.退出系统\n");
printf("\n");
}
fflush(stdin);
}
void print(LNode *h){ //打印函数,定义r为头结点之后的结点,遍历单链表输出
LNode *r;
printf("\n");
printf("输出链表内容为:\n");
printf("\n");
r=h->next;
while(r!=NULL){
printf("%d\t",r->data);
r=r->next;
}
printf("\n");
}
void insert(LNode *h){ //插入函数
LNode *p,*q,*s;
int x;
printf("\n");
printf("输入插入的数x的值为:\n");
printf("\n");
scanf("%d",&x);
s=(LNode*)malloc(sizeof(LNode));
p=h->next;
q=h;
s->data=x;
while(p!=NULL&&p->data<=x){
q=p;
p=p->next;
}
if(p&&(p->data>=x)){
s->next=p;
q->next=s;
}
else{
s->next=NULL;
q->next=s;
}
return;
}
void change(LNode *h){ //逆置函数
LNode *p,*q;
if(h->next==NULL)return;
if((h->next)->next==NULL)return;
p=(h->next)->next;
(h->next)->next=NULL;
while(p!=NULL){
q=p;
p=p->next;
q->next=h->next;
h->next=q;
}
}
LNode *create(){ //创建链表函数
int n;
LNode *head,*p,*q;
head=(LNode*)malloc(sizeof(LNode));
q=head;
printf("\n");
printf("输入元素个数:\n");
scanf("%d",&n);
printf("\n");
if(n>0){
printf("请输入数字:\n");
printf("\n");
while(n>0) {
p=(LNode*)malloc(sizeof(LNode));
scanf("%d",&p->data);
q->next=p;
q=p;
n--;
}
}
q->next=NULL;
return(head);
}
void hebing(LNode *h,LNode *m,LNode *c) //合并逆序函数
{
LNode *pa,*pb,*s;
pa=h->next;
if(pa->data>pa->next->data)
change(h);
pa=h->next;
pb=m->next;
c=h;
c->next=NULL;
free(m);
while(pa!=NULL&&pb!=NULL)
{
if(pa->data<pb->data)
{
s=pa;
pa=pa->next;
}
else
{
s=pb;
pb=pb->next;
}
s->next=c->next;
c->next=s;
}
if(pa==NULL)
pa=pb;
while(pa!=NULL)
{
s=pa;
pa=pa->next;
s->next=c->next;
c->next=s;
}
print(h);
return;
}