/******************************************************************************************
****题目3: ***
****假设有两个按元素值递增有序的线性表A和B,均以单链表作存储结构,试编写算法将A表和B表 ***
****归并成一个按元素值递减有序的线性表C,并要求利用原表的空间存放C。 ***
*******************************************************************************************/
//本算法的基本思想是:先将A,B逆序,然后再进行插入!形成一个新的链表。
#include "iostream"
using namespace std;
typedef int datatype;
typedef struct node
{
datatype data;
struct node *next;
}linklist;
linklist *creat_linklist_head(void)
{
datatype ch;
linklist *head,*rear,*s;
head = (linklist *)malloc(sizeof(linklist));
rear = head;
cin>>ch;
while (ch!=-1)
{
s = (linklist *)malloc(sizeof(linklist));
s->data = ch;
rear->next = s;
rear = s;
cin>>ch;
}
rear->next = NULL;
return head;
}
void print_linklist(linklist *head)
{
linklist *L;
L = head->next;
while (L)
{
cout<<L->data<<'\t';
L = L->next;
}
cout<<endl;
}
linklist *turn_around(linklist *head)
{
linklist *p,*q,*r,*temp;
p = head->next;
temp = head->next;
if (!p)
return head;
else
{
q = head->next->next;
if (!q)
return head;
else
{
r = q->next;
if (!r)
{
q->next = p;
p->next = NULL;
head->next = q;
return head;
}
else
{
while (r)
{
q->next = p;
p = q;
q = r;
r = r->next;
}
q->next = p;
head->next = q;
temp->next = NULL;
return head;
}
}
}
}
linklist * link_two_linklist (linklist *A,linklist *B)
{
linklist *a,*b,*rear,*C;
a = A->next;
b = B->next;
C = A;
C->next = NULL;
if (!a || !b)
{
if (!a)
return B;
else
return A;
}
rear = C;
while (a && b)
{
if (a->data >= b->data)
{
rear->next = a;
rear = a;
a = a->next;
}
else
{
rear->next = b;
rear = b;
b = b->next;
}
}
if (!a)
{
rear->next = b;
}
else
{
rear->next = a;
}
return C;
}
void main(void)
{
linklist *A,*B,*C;
A = creat_linklist_head();
B = creat_linklist_head();
C = turn_around(A);
C = turn_around(B);
print_linklist(A);
print_linklist(B);
C = link_two_linklist(A,B);
print_linklist(C);
}