160. Intersection of Two Linked Lists
来源:互联网 发布:搜款网广州网络批发1 编辑:程序博客网 时间:2024/06/03 15:50
若是两个相同长度的链表则对比相应位置处的地址则可以得到交集。先求出两个链表的长度,再求出差值,将长的去掉差值个元素再比较相应位置的元素。
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { int len1=0,len2=0; ListNode*l1=headA,*l2=headB; if(!headA||!headB) return null; while(l1){ l1=l1->next; len1++; } while(l2){ l2=l2->next; len2++; } int gap=len1-len2; if(gap>0){ while(gap--) headA=headA->next; }else{ while(-(gap++)>0) headB=headB->next; } while(headA){ if(headA==headB) return headA; headA=headA->next; headB=headB->next; } return NULL; }
int型的全局变量会初始化为0,局部变量会任意分陪一个。
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode*l1=headA,*l2=headB; if(!l1||!l2) return NULL; // if() while(l1!=l2){ if(!l1) { l1=headB; continue; } if(!l2) { l2=headA; continue; } l1=l1->next; l2=l2->next; } return l1; }
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode*l1=headA,*l2=headB; if(!l1||!l2) return NULL; // if() while(l1!=l2){ l1=l1?l1->next:headB; l2=l2?l2->next:headA; } return l1; }
阅读全文
0 0
- [LeetCode]160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160.Intersection of Two Linked Lists
- [leetcode] 160.Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 【LeetCode】160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- drawable-xhdpi和drawable-xxxhdpi的区别
- 如何使计算机安全技术有效应用
- 从0到1,开启vue_mobile---axios再学习
- i++是原子操作吗?怎么保证其原子性
- 网络编程作业2
- 160. Intersection of Two Linked Lists
- 发布应用时控制log日志输出
- 雄安新区 行政范围经纬度坐标
- Linux环境下安装TPC-H与数据导入PostgreSQL
- excel的生成与表头的合并的一个例子
- 三十、安装第三方模块
- iOS开发日志:多屏幕适配
- 学习《如何提升你的能力?给年轻程序猿的几条建议》文章笔记
- 电脑注册多个版本的tomcat为系统服务