Intersection of Two Linked Lists
2015-10-06 22:48
453 查看
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
Runtime: 72ms
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return
null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
Runtime: 72ms
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(!headA || !headB) return NULL; if(getLength(headA) > getLength(headB)){ int len = getLength(headA); while(len > getLength(headB)){ headA = headA->next; len--; } } else{ int len = getLength(headB); while(len > getLength(headA)){ headB = headB->next; len--; } } while(headA){ if(headA == headB) return headA; headA = headA->next; headB = headB->next; } return NULL; } int getLength(ListNode* head){ int result = 0; while(head){ head = head->next; result++; } return result; } };
相关文章推荐
- 收藏几个安卓镜像地址
- CentOS7下mariaDB和phpmyadmin的一些安装和配置问题
- 解决 js 中文乱码问题小技巧
- 用python进行项目实训的计划
- Linux-3.0.35 I2C使用说明
- HTML5 canvas画图
- CentOS7下mariaDB和phpmyadmin的一些安装和配置问题
- React 组件协同关系
- 【Python】Learn Python the hard way, ex5 格式化字符串
- 日志二人转——Log4j与JCL小探
- 如何用LINUX命令格式化U盘
- 华为OJ(求字符串中最后一个单词的长度)
- 和声搜索算法-python实现
- ios 页面跳转
- 网站地图
- 内核通知链原理及机制
- 微信刷粉任务平台使用教程
- vector中erase用法注意事项
- c++笔试题:简易学生信息系统
- iOS---小经验分享