leetcode 160:Intersection of Two Linked Lists
来源:互联网 发布:jira mysql驱动 win7 编辑:程序博客网 时间:2024/06/10 19:58
问题描述:
Write a program to find the node at which the intersection of two singly linked lists begins.
思路:
题目说O(n)时间解决问题。求两条list的相交点,可以首先求出两条list的长度差,然后调整使得两个指针同步到达相交点,那么相交点就可以得到。
代码:
class Solution {public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { int lengthA = 0, lengthB = 0; ListNode *count_p; //count listA count_p = headA; while (count_p != NULL) { lengthA++; count_p = count_p->next; } //count listB count_p = headB; while (count_p != NULL) { lengthB++; count_p = count_p->next; } ListNode *nowA, *nowB; nowA = headA; nowB = headB; //align the two lists int dif = lengthA - lengthB; if (dif < 0) //listB is longer { for (int i = 0; i < -dif; i++) { nowB = nowB->next; } } if (dif > 0) //listA is longer { for (int i = 0; i < dif; i++) { nowA = nowA->next; } } while (nowA != nowB) { nowA = nowA->next; nowB = nowB->next; } return nowA; }};
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
- 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
- [LeetCode][160][Intersection of Two Linked Lists ]
- leetcode-160 Intersection of Two Linked Lists
- leetcode 160Intersection 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
- [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
- 快速查看Mac下软件的所有快捷键— CheatSheet
- leetcode:Roman to Integer
- 继承AppCompatActivity如何实现无标题
- Rational Rose Enterprise Edition安装使用
- 学习笔记5
- leetcode 160:Intersection of Two Linked Lists
- java如何将一个序列化对象添加到压缩文件中
- 使用ServerSocketChannel与SocketChannel实现的CS模式
- UI基础-05 HelloWorld 工程中的故事板文件
- xwiki 7.14 Windows安装教程(jetty + MySQL5.7+jdk1.7)
- Java中 ==和equals方法的区别
- 在程序中添加广告
- 蓝桥杯 未名湖边的烦恼 (算法训练)
- 信息提醒之对话框(AlertDialog + ProgressDialog)-更新中