单链表

#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct STU{
char name[20];
char stuno[10];
int age;
int score;
}stu[50];
typedef struct STU ElemType ;
struct LNODE
{
ElemType data;
struct LNODE *next;
};
typedef struct LNODE LNode ;
typedef struct LNODE *LinkList;


int init(LinkList *L)
{
*L=(LNode *)malloc(sizeof(LNode));
if(!L)
exit(0);
memset(&((*L)->data),0,sizeof(struct STU));
(*L)->next=NULL;
return 1;
}/*  init*/


int GetElem(LinkList L,int i,ElemType *e)
{
LinkList p;
int j;

p=L->next;
j=1;


while(p && j<i)
{
p=p->next;
++j;
}
if(!p || j>i) return 0;


*e=p->data;
return 1;
}


int ListInsert(LinkList L, int i, ElemType e)
{
LinkList p,s;
int j;


p=L;j=0;
while(p && j<i-1)
{
p=p->next;
++j;
}
if(!p || j>i-1)  return 0;


s=(LinkList)malloc(sizeof(LNode));
s->data=e;


s->next=p->next;
p->next=s;
return 1;


}/*inset  before i*/
int ListDel(LinkList L, int i)
{
LinkList p,s;
int j;


p=L;
j=0;
while(p && j<i-1)
{
p=p->next;
++j;
}
if(!p || j>i-1)  return 0;
p->next=p->next->next;
return 1;


}/*del at i*/
void MergeList(LinkList La, LinkList Lb, LinkList *Lc)
{
LinkList pa, pb, pc;
pa=La->next;
pb=Lb->next;
*Lc=pc=La;
while(pa && pb)
{
if(Less_EqualList(&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);

}


int Less_EqualList(ElemType *e1,ElemType *e2)
{
if(strcmp(e1->name,e2->name)<=0)
return 1;
else
return 0;
}
int printList(LinkList L)
{
int i;
LinkList p;
p=L;
printf("name       stuno        age     score\n");
while(p->next)
{
p=p->next;
printf("%-10s %s\t%d\t%d\n",p->data.name,p->data.stuno,p->data.age,p->data.score);
}
printf("\n");
}
int main()
{
struct STU e;
LinkList La, Lb, Lc;
printf("\n\n-----------------------------List Demo is running...---------\n\n");
printf("First is InsertList function.\n");
init(&La);
strcpy(e.name,"stu1");
strcpy(e.stuno,"100001");
e.age=80;
e.score=1000;
ListInsert(La,1,e);


strcpy(e.name,"stu3");
strcpy(e.stuno,"100002");
e.age=80;
e.score=1000;
ListInsert(La,2,e);


printList(La);
getchar();




strcpy(e.name,"stu5");
strcpy(e.stuno,"100003");
e.age=80;
e.score=1000;
ListInsert(La,3,e);
printList(La);
getchar();




init(&Lb);
strcpy(e.name,"stu2");
strcpy(e.stuno,"100001");
e.age=80;
e.score=1000;
ListInsert(Lb,1,e);
strcpy(e.name,"stu4");
strcpy(e.stuno,"100002");
e.age=80;
e.score=1000;
ListInsert(Lb,2,e);
strcpy(e.name,"stu6");
strcpy(e.stuno,"100001");
e.age=80;
e.score=1000;
ListInsert(Lb,3,e);
printList(Lb);
getchar();


MergeList(La,Lb,&Lc);
printList(Lc);
ListDel(Lc,1);
printList(Lc);
getchar();


return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值