判断两单链表是否相交
来源:互联网 发布:2016网络最热门话题 编辑:程序博客网 时间:2024/06/06 00:49
#include <stdio.h>struct Node{ int data; struct Node * next;};struct Node * FindLoopPort(struct Node * head){ struct Node * slow = head, *fast = head; while(fast && fast->next ) { slow = slow->next; fast = fast->next->next; if ( slow == fast ) break; } if (fast == NULL || fast->next == NULL) return NULL; slow = head; while(slow != fast) { slow = slow->next; fast = fast->next; } return slow;}struct Node * FindTail(struct Node * head){ while(head) { if(!head->next) break; head = head->next; } return head;}bool IsIntersect(struct Node * head1, struct Node * head2){ struct Node * port1 = FindLoopPort(head1); struct Node * port2 = FindLoopPort(head2); if(port1 == NULL && port2 == NULL) { struct Node * tail1 = FindTail(head1); struct Node * tail2 = FindTail(head2); if(tail1 == tail2) { return true; } } else if(port1 != NULL && port2 != NULL) { struct Node * port3 = port1; do { if(port1 == port2) { return true; } port1 = port1->next; }while(port1 != port3); } return false;}int main(){ struct Node * node1 = new Node(); node1->data = 1; node1->next = NULL; struct Node * node2 = new Node(); node2->data = 2; node2->next = NULL; struct Node * node3 = new Node(); node3->data = 3; node3->next = NULL; struct Node * node4 = new Node(); node4->data = 4; node4->next = NULL; struct Node * node5 = new Node(); node5->data = 5; node5->next = NULL; struct Node * node6 = new Node(); node6->data = 6; node6->next = NULL; struct Node * node7 = new Node(); node7->data = 7; node7->next = NULL; struct Node * node8 = new Node(); node8->data = 8; node8->next = NULL; struct Node * node9 = new Node(); node9->data = 9; node9->next = NULL; struct Node * node10 = new Node(); node10->data = 10; node10->next = NULL; node1->next = node2; node2->next = node3; node3->next = node4; node4->next = node5; node5->next = node6; node6->next = node3; node7->next = node5; printf("%d\n", IsIntersect(node1, node7)); return 0;}
阅读全文
0 0
- 判断两单链表是否相交
- 判断单链表是否存在环,判断两单链表是否相交
- 判断俩个链表是否相交
- 判断俩链表是否相交
- 判断俩个链表是否相交
- 判断俩链表是否相交
- 判断矩形是否相交
- 判断俩个链表是否相交
- 判断两条单链表是否相交
- 判断这俩个链表是否相交
- 判断两链表是否相交
- 判断俩个链表是否相交
- 判断线段是否相交
- 判断俩单链表是否相交
- 判断两链表是否相交
- 判断无环链表是否相交
- 判断有环链表是否相交
- 单链表判断是否相交
- 基于开源项目搭建属于自己的技术堆栈
- SpringMVC类型转换、数据绑定详解[附带源码分析]
- spring切面表达式简单解析
- 2017/10/30计划
- 小白自学Python3爬虫
- 判断两单链表是否相交
- redis缓存和cookie实现Session共享
- linux常用知识
- 软件开发中各个字符集之间的区别
- 机器学习:决策树
- Python数据可视化
- 基于概率论的分类方法:朴素贝叶斯
- kafka安装命令记录
- Flex布局怎么用--一个图文列表页的实现