/* Note:Your choice is C IDE */
#include "stdio.h"
#include"malloc.h"
#include"stdlib.h"//包含exit()函数的头文件,以及system("pause")
#define OK 1
#define error 0
#define OVERFLOW -1
typedef int Status;
typedef int ElemType;
/*-------------struct------------*/
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode ,*linklist;
/*-------------Init------------*/
Status InitList_L(linklist *L){
(*L)=(linklist)malloc(sizeof(LNode));
if(!*L)exit(OVERFLOW);
(*L)->next=NULL;
return OK;
}
/*-------------Insert------------*/
Status ListInsert_L(linklist *L,int i,ElemType e){
linklist p,p1;
int j=0;
p1=*L;
while(p1&&j<i-1){
p1=p1->next;
++j;
}
if(!p1||j>i-1)return error;
p=(linklist)malloc(sizeof(LNode));
if(!p)exit(OVERFLOW);
p->data=e;
p->next=p1->next;
p1->next=p;
return OK;
}
/*-------------delete------------*/
Status ListDelete_L(linklist *L,int i,ElemType *e){
linklist p,q;
int j=0;
p=*L;
while(p->next&&j<i-1)
{
p=p->next;
++j;
}
if(!(p->next)||j>i-1) return error;
q=p->next;
p->next=q->next;
*e=q->data;
free(q);
return OK;
}
/*-------------merge------------*/
Status MergeList_L(linklist *L1,linklist *L2,linklist *L3)
{
linklist p3,p1,p2;
p1=(*L1)->next;
p2=(*L2)->next;
*L3=p3=*L1;
while(p1&&p2){
if(p1->data<p2->data){
p3->next=p1;
p3=p1;
p1=p1->next;
}
else{
p3->next=p2;
p3=p2;
p2=p2->next;
}
}
p3->next=p1?p1:p2;
free(*L2);
return OK;
}
int main()
{
int i,e,n;
linklist L1,L2,L3,p;
if(InitList_L(&L1))printf("Init L1 is ok.\n");
if(InitList_L(&L2))printf("Init L2 is ok.\n");
printf("Please enter a value for n of L1:\n");
scanf("%d",&n);
printf("Please enter n values for L1:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&e);
if(ListInsert_L(&L1,i,e)!=OK) break;
}
printf("The current elements of L1 are:\n");
p=L1->next;
printf ("L1->");
for(i=1;i<=n;i++){
printf("%d—>",p->data);
p=p->next;
}
printf("NULL\n");
printf("Please enter a value for n of L2:\n");
scanf("%d",&n);
printf("Please enter n values for L2:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&e);
if(ListInsert_L(&L2,i,e)!=OK) break;
}
printf("The current elements of L2 are:\n");
p=L2->next;
printf ("L2->");
while(p){
printf("%d—>",p->data);
p=p->next;
}
printf("NULL\n");
printf("下面进入合并操作:\n");
MergeList_L(&L1,&L2,&L3);
printf("The current elements of L3 are:\n");
p=L3->next;
printf ("L3->");
while(p){
printf("%d—>",p->data);
p=p->next;
}
printf("NULL\n");
printf("下面进入删除操作:\n");
printf("Please enter a value for i:\n");
scanf("%d",&i);
if(ListDelete_L(&L1,i,&e))
printf("The deleted elem is :%d\n",e);
else printf("删除失败\n");
printf("The current elements of L3 are:\n");
p=L3->next;
printf ("L3->");
while(p){
printf("%d—>",p->data);
p=p->next;
}
printf("NULL\n");
system("pause");
return 0;
}
程序运行截图