您的位置:首页 > 理论基础 > 数据结构算法

将两个递增有序的单链表合并成一个递减有序的单链表,利用原结点空间

2017-05-10 09:36 459 查看

两种方法

新建链表,依次分离原链表结点插入到新链表上

依然使用其中一个原链表,将另一个链表中的结点依次插入

这里使用第一种方法

代码如下

#include<iostream>
#include<vector>
#include<algorithm>

#include<cstdio>
#include<cstdlib>
#include<ctime>

using namespace std;

typedef struct Node_ {
int data;
struct Node_ * next;
}Node, * List;

void Union( List &A, List &B, List &C );
void Print( List A );

int main( )
{
vector<int> V1, V2;
srand( (unsigned)time( 0 ) );
for( int i = 0; i < 50; i++ ) {
V1.push_back( rand( ) % 50 + 1 );
V2.push_back( rand( ) % 50 + 1 );
}
sort( V1.begin(), V1.end() );
sort( V2.begin(), V2.end() );

/* creat two lists */

List L1 = new Node;
List L2 = new Node;
List R1, R2;

R1 = L1;
R2 = L2;
L1->next = nullptr;
L2->next = nullptr;

for( int i = 0; i < 50; i++ ) {
List S1 = new Node;
List S2 = new Node;

S1->data = V1[i];
R1->next = S1;
R1 = S1;
S2->data = V2[i];
R2->next = S2;
R2 = S2;
}
R1->next = R2->next = nullptr;

/* delete the header */
List Temp;
Temp = L1;
L1 = L1->next;
delete Temp;
Temp = L2;
L2 = L2->next;
delete Temp;

/* 合并为非增有序链表 */

List L3 = nullptr;
Union( L1, L2, L3 );
Print( L3 );

getchar( );
return 0;
}

/*这里A,B也用引用是因为要避免原来的两个链表指针变成野指针*/
void Union( List &A, List &B, List &C )
{
C = new Node;
C->next = nullptr;

while( A != nullptr && B != nullptr ) {
List S;

if( A->data < B->data ) {
S = A;
A = A->next;
}
else {
S = B;
B = B->next;
}
S->next = C->next;
C->next = S;
}
if( A == nullptr )
A = B;
List S;
while( A != nullptr ) {
S = A;
A = A->next;
S->next = C->next;
C->next = S;
}

List Temp = C;
C = C->next;
delete Temp;
}
void Print( List A )
{
while( A != nullptr ) {
cout << A->data << "\t";
A = A->next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐