两个链表交集操作(考试用)
基于之前给出的是使用散列标记的优化算法,适合编程不适合考试。所以接着给出暴力法的代码供诸位应付考试:
这是之前用散列优化过的:https://blog.csdn.net/qq_41938259/article/details/83820352

void intersection(lnode *ha, lnode *hb, lnode *&hc)
{
//下面两行用于初始化hc链表
//hc用于存放交集的集合
hc = new lnode;
hc->next = NULL;
//pa指针用于遍历链表ha
//pb指针用于遍历链表hb
//s指针指向hc链表创建出的新节点
lnode *pa = ha->next, *pb, *s;
while (pa)//外层循环遍历链表pa
{
pb = hb->next;
while (pb)
{
if (pa->data != pb->data)
pb = pb->next;//pa不动时pb指针后移
else
{
//当两集合中某一值相同时,取出该值
//并创建节点s再插入链表hc
s = new lnode;
s->data = pb->data;
s->next = hc->next;
hc->next = s;
pb = NULL;//回溯法,跳出while循环
}
}
pa = pa->next;//pa指针后指
}
}
注释自以为很详细了。。。
这是完整的:
include<iostream>
#include<stdlib.h>
using namespace std;
class node
{
public:
node* next;
int data;
node() {}
~node() {}
node* create();
int del(node* head);
};
node* node::create()
{
node *p, *pa, *head;
head = new node;
head->next = NULL;
pa = head;
int n;
cout << "输入总个数:";
cin >> n;
for (int i = 0; i < n; i++)
{
p = new node;
int a;
cin >> a;
p->data = a;
p->next = NULL;
pa->next = p;
pa = p;
}
return head;
}
int node::del(node* head)
{
int n;
cout << "查找是否存在该数,并删除:";
cin >> n;
int x = 0;
node* p = head->next;
node* pa = head;
while (p != NULL)
{
if (p->data == n)
{
x = 1;
pa->next = p->next;
delete(p);
p = pa->next;
}
else
{
pa = p;
p = p->next;
}
}
return x;
}
void print(node* head)
{
node *p;
p = head->next;
while (p)
{
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}
void intersection(node *ha, node *hb, node *&hc)
{
//下面两行用于初始化hc链表
//hc用于存放交集的集合
hc = new node;
hc->next = NULL;
//pa指针用于遍历链表ha
//pb指针用于遍历链表hb
//s指针指向hc链表创建出的新节点
node *pa = ha->next, *pb, *s;
while (pa)//外层循环遍历链表pa
{
pb = hb->next;
while (pb)
{
if (pa->data != pb->data)
pb = pb->next;//pa不动时pb指针后移
else
{
//当两集合中某一值相同时,取出该值
//并创建节点s再插入链表hc
s = new node;
s->data = pb->data;
s->next = hc->next;
hc->next = s;
pb = NULL;//回溯法,跳出while循环
}
}
pa = pa->next;//pa指针后指
}
}
int main(void)
{
node A;
node B;
node* C;
node* L = A.create();
node* l = B.create();
intersection(L,l,C);
print(C);
system("pause");
return 0;
}

浙公网安备 33010602011771号