集合的运算之链表实现
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; }
相关文章推荐
- 1770: [Usaco2009 Nov]lights 燈 高斯消元解异或方程组+dfs
- 2416开发记录十二:ioremap
- React Webpack cookbook
- json格式的数组长度
- 怎样改动Myeclipse10.7的Servlet模板
- HDoj-1527-取石子游戏
- 10大白帽黑客专用的 Linux 操作系统
- hadoop(八) - sqoop安装与使用
- 小众软件
- 构建LAMP平台(三)(软件版本:httpd-2.4.16,php-5.6.12,mysql-5.6.26)
- 构建LAMP平台(二)(使用xcache-2.0给php加速)
- 程序无法启动ALL_BUILD 拒绝访问
- Wc2016酱油记
- 3.4 复杂进度对话框
- 关于ObjectOutputStream
- SpatialHdoop中空间索引的构建
- 如何利用支付宝集福(敬业福)引流
- MatLab 组件大全
- Android实现网络多线程断点续传下载
- ActiveMQ集群(2)