判断两个链表是否相交
方法:获得两个链表的长度,获得长度的差值len,然后首先遍历较长的链表len次,然后再同时遍历两个链表,如果有相同部分,两个链表就相交,如果没有,则不相交,即没有公共部分。
代码:
#include <iostream> #include <cstdlib> using namespace std; typedef struct list{ int data; struct list *next; }*listNode; void initList(listNode &list) //初始化程序 { list=( struct list*) malloc ( sizeof ( struct list)); list->data=0; list->next=NULL; } void createList(listNode &list, int a[], int n) //创建链表 { listNode head,node; head=list; for ( int i=0;i<n;i++) { node=( struct list*) malloc ( sizeof ( struct list)); node->data=a[i]; node->next=NULL; head->next=node; head=node; } } void judgeInter(listNode list,listNode list1) //判断两个链表是否相交 { int len1=0,len2=0; listNode head,head1; head=list->next; //获得两个链表的长度 while (head) { len1++; head=head->next; } head=list1->next; while (head) { len2++; head=head->next; } int t=len1-len2; head=list; head1=list1; while (t>0) { head=head->next; t--; } while (len2>0) //判断有没有相同的部分 { head=head->next; head1=head1->next; if (head->data==head1->data) { cout<< "the two list have the same part:" << " " <<head->data<<endl; break ; } len2--; } if (len2<=0) cout<< "the two list dont have the same list" <<endl; } void playList(listNode list) //输出单链表 { listNode head; head=list->next; if (head==NULL) cout<< "the list is null" <<endl; while (head) { cout<<head->data<< "--" ; head=head->next; } cout<<endl; } int main() { listNode list,list1; int a[10]={1,2,3,4,5,6,7,8,9,0}; int b[8]={12,13,16,17,11,8,9,0}; initList(list); initList(list1); cout<< "create the list:" <<endl; createList(list,a,10); createList(list1,b,8); cout<< "output the list:" <<endl; playList(list); playList(list1); cout<<endl; judgeInter(list,list1); cout<<endl; return 0; } |
运行截图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述