#include<stdio.h>
#include<stdlib.h>
typedef int LElemType;
typedef struct LNode{
LElemType date;
struct LNode *next;
}LNode,*Linklist;
void CreateLinkList(Linklist &L,int n){
Linklist pre,p;
L=(Linklist)malloc(sizeof(LNode));
pre=L;
for(int i=0;i<n;i++){
p=(Linklist)malloc(sizeof(LNode));
scanf("%d",&p->date);
pre->next=p;
pre=p;
}
pre->next=NULL;
}
void CreateList_Head(Linklist &L,int n){
L=(Linklist)malloc(sizeof(LNode));
L->next=NULL;
Linklist p;
for(int i=0;i<n;i++){
p=(Linklist)malloc(sizeof(LNode));
scanf("%d",&p->date);
p->next=L->next;
L->next=p;
}
}
int ListIsEmpty(Linklist L){
if(L->next)
return 1;
return 0;
}
int ListLength(Linklist L){
int count=0;
Linklist p;
p=L->next;
while(p){
count++;
p=p->next;
}
return count;
}
void GetElem(Linklist L,int i,LElemType &e){
int j=1;
Linklist p;
p=L->next;
while(p&&j<i){
j++;
p=p->next;
}
if(j>i||!p){
exit(0);
}
e=p->date;
}
void ListInsert(Linklist &L,int i,LElemType e){
int j=0;
Linklist p,s;
p=L;
while(p&&j<i-1){
j++;
p=p->next;
}
if(!p||j>i-1)
exit(0);
s=(Linklist)malloc(sizeof(LNode));
s->date=e;
s->next=p->next;
p->next=s;
}
int LocateElem(Linklist L,LElemType e){
int j=1;
Linklist p;
p=L->next;
while(p&&p->date!=e){
j++;
p=p->next;
}
if(!p)
return 0;
return j;
}
void ListDelete(Linklist &L,int i,LElemType &e){
int j=0;
Linklist p,s;
p=L;
while(p->next&&j<i-1){
j++;
p=p->next;
}
if(!p->next||j>i-1)
exit(0);
s=p->next;
p->next=s->next;
e=s->date;
free(s);
}
void traverse(Linklist L){
while(L->next){
L=L->next;
printf("%d\n",L->date);
}
}
void Reverse(Linklist &L){
Linklist p,q;
p=L->next;
L->next=NULL;
while(p){
q=p;
p=p->next;
q->next=L->next;
L->next=q;
}
}
void ListMerge(Linklist &L1,Linklist &L2,Linklist &L3){
Linklist pre,pa,pb;
pre=pa;
L3=pre;
pa=L1->next;
pb=L2->next;
while(pa&&pb){
if(pa->date<=pb->date){
pre->next=pa;
pre=pa;
pa=pa->next;
}
else{
pre->next=pb;
pre=pb;
pb=pb->next;
}
}
if(pa)
pre->next=pa;
else
pre->next=pb;
free(L2);
}
void deleteValue(Linklist &L3)
{
Linklist p, q, r;
p = L3->next;
while(p)
{
r = p;
while(r->next)
{
if (r->next->date == p->date)
{
q = r->next;
r->next = q->next;
free(q);
}
else
r = r->next;
}
p = p->next;
}
}
int main()
{
Linklist L,L1,L2,L3;
int n,m;
printf("输入建立链表的长度---\n");
scanf("%d",&n);
CreateLinkList(L,n);
traverse(L);
printf("---------------------\n");
Reverse(L);
traverse(L);
printf("---------------------\n");
printf("输入建立两个链表的长度---\n");
scanf("%d%d",&n,&m);
CreateLinkList(L1,n);
CreateLinkList(L2,m);
traverse(L1);
printf("---------------------\n");
traverse(L2);
printf("---------------------\n");
ListMerge(L1,L2,L3);
deleteValue(L3);
traverse(L3);
return 0;
}
1.2单链表的操作
最新推荐文章于 2022-09-05 23:36:49 发布