单链表
包括归并两个有序链表到一个有序链表
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}List,*LNodeList;
ElemType GetElem(LNodeList &L,int num)
{
LNodeList p=L;
int i=0;
while(p!=NULL && i<num)
{
p=p->next;
i++;
}
return p->data;
}
int GetIndex(LNodeList &L,ElemType x)
{
LNodeList p;
int i=0;
p=L->next;
while(p!=NULL && p->data!=x)
{
p=p->next;
i++;
}
if(p->data==x)
return i+1;
else
printf("cannot find this value int the list! \n");
exit(0);
}
void InsertList(LNodeList &L,int index,ElemType data)
{
LNodeList p=L;
int i=0;
while(p!=NULL && i<index-1)
{
p=p->next;
i++;
}
if(p==NULL)
{
printf("p==NULL!!");
exit(0);
}
if(!p || i>index-1)
{
printf("the index out of length of list!!");
exit(0);
}
LNodeList s=(LNodeList)malloc(sizeof(LNode));
s->data=data;
s->next=p->next;
p->next=s;
}
void DeleteList(LNodeList &L,int index)
{
LNodeList p=L;
int i=0;
while(p!=NULL && i<index-1)
{
p=p->next;
i++;
}
if(!p || i>index-1)
{
printf("the index out of length of list!!");
exit(0);
}
LNodeList s=p->next;
p->next=s->next;
free(s);
}
void MergeList(LNodeList &La,LNodeList &Lb,LNodeList &Lc)
{
LNodeList pa,pb,pc;
pa=La->next;
pb=Lb->next;
pc=Lc=Lb;
while(pa && pb)
{
if(pa->data <= pb->data)
{
pc->next=pa;
pc=pa;
pa=pa->next;
}
else
{
pc->next=pb;
pc=pb;
pb=pb->next;
}
}
pc->next=pa?pa:pb;
free(Lb);
free(La);
}
void CreatList(LNodeList &L,int num)
{
LNodeList p;
srand(time(NULL));
L=(LNodeList)malloc(sizeof(LNode));
L->next=NULL;
for(int i=0;i<num;i++)
{
p=(LNodeList)malloc(sizeof(LNode));
p->data=rand()%100;
p->next=L->next;
L->next=p;
}
}
void CreatListArray(LNodeList &L,int array[],int num)
{
LNodeList p;
L=(LNodeList)malloc(sizeof(LNode));
L->next=NULL;
for(int i=0;i<num;i++)
{
p=(LNodeList)malloc(sizeof(LNode));
p->data=array[i];
p->next=L->next;
L->next=p;
}
}
void PrintList(LNodeList L)
{
LNodeList p;
p=L->next;
printf("Show all list element:");
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main(void)
{
int a[5]={9,7,5,3,1};
int b[5]={10,8,6,4,2};
LNodeList L;
CreatListArray(L,a,5);
PrintList(L);
LNodeList L2;
CreatListArray(L2,b,5);
PrintList(L2);
LNodeList L3;
MergeList(L,L2,L3);
PrintList(L3);
int i,j;
printf("please input the index that you want to find:");
scanf("%d",&i);
printf("the %d index value is %d \n",i,GetElem(L3,i));
printf("please input the value that you want to find:");
scanf("%d",&i);
printf("the %d index value is %d \n",i,GetIndex(L3,i));
printf("please input the index and value that you want to insert:");
scanf("%d %d",&i,&j);
InsertList(L3,i,j);
PrintList(L3);
printf("please input the index that you want to delete:");
scanf("%d",&i);
DeleteList(L3,i);
PrintList(L3);
}