#include <iostream>
using namespace std;
#define LENGTH1 6
#define LENGTH2 10
typedef struct node{
int data;
node* next;
} *List;
//typedef node* List;
List mergeList(List &list1,List &list2)
{
List list,temp;
List tempList=new node;
list=tempList;
List pList1 = list1;
List pList2 = list2;
List pCurNode = NULL;
while(pList1 && pList2)
{
if (pList1->data <= pList2->data)
{
pCurNode = pList1;
pList1 = pList1->next;
}
else if (pList1->data > pList2->data)
{
pCurNode = pList2;
pList2 = pList2->next;
}
tempList->data=pCurNode->data;
temp=tempList;
tempList->next=new node;
tempList=tempList->next;
}
tempList=temp;
if (pList1 == NULL && pList2 == NULL)
{
tempList->next=NULL;
return list;
}
List rest = (pList1 != NULL) ? pList1 : pList2;
tempList->next=rest;
return list;
}
//若第K大的值存在则返回第K大的值,否则返回-1;
int findK(List &list1, List &list2, int k)
{
List pList1 = list1;
List pList2 = list2;
List pCurNode = NULL;
int count = 0;
while(pList1 && pList2)
{
if (pList1->data <pList2->data)
{
pCurNode = pList1;
int temp = pList1->data;
pList1= pList1->next;
while(pList1)
{
if (pList1->data != temp)
{
break;
}
pList1= pList1->next;
}
count++;
}
else if (pList1->data > pList2->data)
{
pCurNode = pList2;
int temp = pList2->data;
pList2= pList2->next;
while(pList2)
{
if (pList2->data != temp)
{
break;
}
pList2= pList2->next;
}
count++;
}
else///相等的时候不计算count值;
{
pCurNode = pList1;
pList1=pList1->next;
}
if (count == k)
{
return pCurNode->data;
}
}
List rest = (pList1 != NULL) ? pList1 : pList2;
while(rest)
{
count++;
if (count == k)
{
return rest->data;
}
int temp = rest->data;
rest= rest->next;
while(rest)
{
if (rest->data != temp)
{
break;
}
rest = rest->next;
}
}
return -1;
}
void display(List &list)
{
List tempList=list;
int cnt=0;
while(tempList)
{
if(cnt==0)
cout<<tempList->data;
else
cout<<","<<tempList->data;
tempList=tempList->next;
cnt++;
}
cout<<endl;
}
void main()
{
int a[LENGTH1]={1,2,3,3,3,5};
int b[LENGTH2]={2,3,3,4,6,7,7,8,8,9};
List list1,tempList1,list2,tempList2,temp;
int i,j,k=4,kLargest;
list1=tempList1=new node;
list2=tempList2=(List)malloc(sizeof(node));
tempList1->data=a[0];
if(LENGTH1==1)
{
tempList1->next=NULL;
}
for(i=1;i<LENGTH1;i++)
{
tempList1->next=new node;
tempList1=tempList1->next;
tempList1->data=a[i];
tempList1->next=NULL;
}
for(j=0;j<LENGTH2;j++)
{
tempList2->data=b[j];
temp=tempList2;
tempList2->next=(List)malloc(sizeof(node));
tempList2=tempList2->next;
}
temp->next=NULL;
List list=mergeList(list1,list2);
cout<<"list1:";
display(list1);
cout<<"list2:";
display(list2);
cout<<"list:";
display(list);
cout<<"请输入K值:";
cin>>k;
kLargest=findK(list1, list2, k);
cout<<"第"<<k<<"大的值为:"<<kLargest<<endl;
}
在两个有序链表中查找第K大元素
最新推荐文章于 2022-07-10 10:11:58 发布