Files
Harmon ec0bab599b ok
2022-05-11 19:11:24 +08:00

123 lines
1.9 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode *next;
} LNode, *LinkList;
// 头插法
void HeadInsert(LinkList &L)
{
int val = 0;
while (cin >> val)
{
LNode *s = new LNode;
s->data = val;
s->next = L->next;
L->next = s;
if (cin.get() == '\n')
{
break;
}
}
}
// 尾插法
void TailInsert(LinkList &L)
{
int val = 0;
LNode *r = L;
while (cin >> val)
{
LNode *s = new LNode;
s->data = val;
r->next = s;
r = s;
r->next = NULL;
if (cin.get() == '\n')
{
break;
}
}
}
// 遍历输出链表元素
void Print(LinkList L)
{
LNode *p = L->next;
while (p)
{
cout << p->data << '\t';
p = p->next;
}
cout << endl;
}
void PublicNode(LinkList &LA, LinkList &LB)
{
LNode *pa, *pb, *r, *q; //定义两个链表的工作结点和尾插指针
pa = LA->next;
pb = LB->next;
r = LA;
while (pa && pb)
{
//如果pa小于pb则将其删除同时指针后移
if (pa->data < pb->data)
{
q = pa;
pa = pa->next;
delete q;
}
else if (pa->data > pb->data)
{
q = pb;
pb = pb->next;
delete q;
}
//如果相等将pa尾插删除pb
else
{
r->next = pa;
r = pa;
pa = pa->next;
q = pb;
pb = pb->next;
delete q;
}
}
//将剩余所有结点全部释放
while (pa)
{
q = pa;
pa = pa->next;
delete q;
}
while (pb)
{
q = pb;
pb = pb->next;
delete q;
}
r->next = NULL;
delete LB;
}
int main()
{
LinkList LA = new LNode;
LinkList LB = new LNode;
TailInsert(LA);
TailInsert(LB);
PublicNode(LA, LB);
Print(LA);
}