您的位置:首页 > 其它

集合的运算之链表实现

2016-02-03 08:13 507 查看
#include <iostream>
using namespace std;

struct Node
{
int content;
Node *next;
};

Node *input();
void output(Node *);
Node *A_or_B(Node *, Node *);
Node *A_and_B(Node *, Node *);
Node *A_not_B(Node *, Node *);
bool is_a(int, Node *);

int main()
{
Node *head_A = input();
Node *head_B = input();
Node *s1 = A_and_B(head_A, head_B);
Node *s2 = A_or_B(head_A, head_B);
Node *s3 = A_not_B(head_A, head_B);
Node *s4 = A_not_B(head_B, head_A);
cout << "A and B is: ";
output(s1);
cout << "A or B is: ";
output(s2);
cout << "A not B is: ";
output(s3);
cout << "B not A is: ";
output(s4);
return 0;
}

Node *input()
{
Node *head = NULL, *tail = NULL;
int x;
cin >> x;
while (x != -1)
{
Node *p = new Node;
p->content = x;
p->next = NULL;
if (head == NULL)
head = tail = p;
else
{
tail->next = p;
tail = p;
}
cin >> x;
}
return head;
}

void output(Node *head)
{
for (Node *p = head; p != NULL; p = p->next)
cout << p->content << " ";
cout << endl;
}

Node *A_and_B(Node *h1, Node *h2)
{
if (h1 == NULL || h2 == NULL)
return NULL;
else
{
Node *head = NULL;
for (Node *h = h2; h != NULL; h = h->next)
if (is_a(h->content, h1))
{
Node *p = new Node;
p->content = h->content;
if (head == NULL)
{
head = p;
p->next = NULL;
}
else
{
p->next = head;
head = p;
}
}
return head;
}
}

Node *A_or_B(Node *h1, Node *h2)
{
if (h1 == NULL)
return h2;
else if (h2 == NULL)
return h1;
else
{
Node *head = NULL, *tail = NULL;
for (Node *h = h1; h != NULL; h = h->next)
{
Node *p = new Node;
p->content = h->content;
p->next = NULL;
if (head == NULL)
head = tail = p;
else
{
tail->next = p;
tail = p;
}
}
for (Node *h = h2; h != NULL; h = h->next)
if (!(is_a(h->content, h1)))
{
Node *p = new Node;
p->content = h->content;
p->next = NULL;
if (head == NULL)
head = tail = p;
else
{
tail->next = p;
tail = p;
}
}
return head;
}
}

Node *A_not_B(Node *h1, Node *h2)
{
if (h1 == NULL)
return NULL;
else if (h2 == NULL)
return h1;
else
{
Node *head = NULL, *tail = NULL;
for (Node *h = h1; h != NULL; h = h->next)
if (!(is_a(h->content, h2)))
{
Node *p = new Node;
p->content = h->content;
p->next = NULL;
if (head == NULL)
head = tail = p;
else
{
tail->next = p;
tail = p;
}
}
return head;
}
}

bool is_a(int i, Node *head)//此函数判断某一个数是否是一个链表中的结点值
{
Node *h = head;
while (h != NULL)
{
if (i == h->content)
return true;
h = h->next;
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: