[leetcode]#160 Intersection of Two Linked Lists
2015-10-21 10:30
363 查看
Write a program to find the node at which the intersection of two singly linked lists begins.
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.
(1)用O(1)空间和O(n)时间,找出两条链表公共部分的起点
解题思路:1、计算两者长度,并判断两个链表尾端是否相同,不同返回null
2、让链表长度较长的走到 (tail的数量 - Btail的数量)步,然后和短链表同步往下走,遇到的第一个相同的节点就是最早的公共节点
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.
(1)用O(1)空间和O(n)时间,找出两条链表公共部分的起点
解题思路:1、计算两者长度,并判断两个链表尾端是否相同,不同返回null
2、让链表长度较长的走到 (tail的数量 - Btail的数量)步,然后和短链表同步往下走,遇到的第一个相同的节点就是最早的公共节点
[code]class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode * tail = headA; ListNode * Btail = headB; int countA = 1, countB = 1, step; if (tail == NULL || headB == NULL) return NULL; while (tail->next != NULL) { tail = tail->next; countA++; } while (Btail->next != NULL) { Btail = Btail->next; countB++; } if (Btail != tail) return NULL; step = countA - countB; tail = headA; Btail = headB; if (step < 0) { step = -step; tail = headB; Btail = headA; } for (int i = 0;i < step; i++) { tail = tail->next; } while (tail != NULL && Btail != NULL && tail !=Btail) { tail = tail->next; Btail = Btail->next; } return tail; } };
相关文章推荐
- css有趣的转换(初学)
- Tomcat启动超时问题Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds
- 美好的大一
- 你不知道的JavaScript--Item13 理解 prototype, getPrototypeOf 和__proto__
- shell实践(一)读取一个文件输出文件内容
- Android——ListView实现简单列表
- MyBatis学习总结(一)——MyBatis快速入门
- 基本数据类型数据对象包装类 小结
- Android——ListView实现简单列表
- tcp的关闭(shutdonw、close、SO_LINGER选项)与 连接断开情形判断
- 跟我学Guava:基础1.2-前置条件
- android 请求服务器,json解析
- ecplise新建项目push到git
- mybatis 多对多 处理
- Java语言基础之Java虚拟机的内存结构
- N个几点的二叉树有多少种形态
- Leetcode110: Subsets
- struts2,hibernate4,spring3配置时问题汇总及解决办法
- C#命名规则和风格(收集)
- 压力测试基本概念