#include<iostream>
#include<stdlib.h>
using namespace std;
#define maxSize 100
typedef struct LNode
{
int data;
struct LNode *next;
} LNode;
void createlistR(LNode *&C,int a[],int n)
{
LNode *s,*r;
C=(LNode*)malloc(sizeof(LNode));
C->next=NULL;
r=C;
for(int i=0; i<n; i++)
{
s=(LNode*)malloc(sizeof(LNode));
s->data=a[i];
r->next=s;
r=r->next;
}
r->next=NULL;
}
void merge(LNode *A,LNode *B,LNode *&C)
{
LNode *p,*q,*r,*s;
p=A->next;
q=B->next;
C=(LNode*)malloc(sizeof(LNode));
C->next=NULL;
r=C;
while(p!=NULL&&q!=NULL)
{
if(p->data<=q->data)
{
s=p;
p=p->next;
s->next=NULL;
r->next=s;
r=r->next;
}
else
{
s=q;
q=q->next;
s->next=NULL;
r->next=s;
r=r->next;
}
}
while(p!=NULL)
{
s=p;
p=p->next;
s->next=NULL;
r->next=s;
r=r->next;
}
while(q!=NULL)
{
s=q;
q=q->next;
s->next=NULL;
r->next=s;
r=r->next;
}
}
void BubbleSort(int a[],int n)
{
int i,j,temp;
for(i=n-1; i>1; --i)
for(j=1; j<=i; ++j)
if(a[j-1]>a[j])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
void printlistR(LNode *C)
{
LNode *s;
s=C->next;
while(s->next!=NULL)
{
cout<<s->data<<" ";
s=s->next;
}
if(s->next==NULL)
cout<<s->data;
cout<<endl<<endl;
}
int main()
{
int a[maxSize];
int n=10;
for(int i=0; i<n; i++)
a[i]=rand()%31;
int b[maxSize];
int m=5;
for(int i=0; i<m; i++)
b[i]=rand()%21;
// cout<<"array list a:"<<endl;
// for(int i=0; i<n; i++)
// cout<<a[i]<<" ";
// cout<<endl<<endl;
//
// cout<<"array list b:"<<endl;
// for(int i=0; i<m; i++)
// cout<<b[i]<<" ";
// cout<<endl<<endl;
BubbleSort(a,n);
BubbleSort(b,m);
// cout<<"array list a after sort:"<<endl;
// for(int i=0; i<n; i++)
// {
// cout<<a[i]<<" ";
// }
// cout<<endl<<endl;
//
// cout<<"array list b after sort:"<<endl;
// for(int i=0; i<m; i++)
// {
// cout<<b[i]<<" ";
// }
// cout<<endl<<endl;
LNode *C;
createlistR(C,a,n);
cout<<"link list C:"<<endl;
printlistR(C);
cout<<endl;
LNode *D;
createlistR(D,b,m);
cout<<"link list D:"<<endl;
printlistR(D);
cout<<endl;
LNode *E;
merge(C,D,E);
cout<<"link list C,D merge into link list E:"<<endl;
printlistR(E);
}
运行结果:

本文介绍了一种使用C++实现的链表数据结构,并详细展示了如何创建链表、合并两个已排序链表以及对数组进行冒泡排序的方法。通过具体的代码示例,深入解析了链表操作和排序算法的实现细节。
3711

被折叠的 条评论
为什么被折叠?



