LeetCode (160) Intersection of Two Linked Lists
来源:互联网 发布:软件研发项目立项报告 编辑:程序博客网 时间:2024/06/05 09:19
题目
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 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.
分析
给定两个链表,求它们的交叉节点。
要求,时间复杂度在O(n)内,空间复杂度为O(1)
两个链表的长度不定,但是交叉节点的后续节点全部相同,所以先求得每个链表的长度
AC代码
/** * 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; ListNode *p = headA, *q = headB; //求出输入两个链表的长度 int lenA = 0, lenB = 0; while (p) { ++lenA; p = p->next; }//while while (q) { ++lenB; q = q->next; }//while //让长的链表先移动多出的节点 p = headA; q = headB; if (lenA > lenB) { int i = 0; while (p && i < lenA - lenB) { p = p->next; ++i; }//while } else{ int j = 0; while (q && j < lenB - lenA) { q = q->next; ++j; }//while } while (p && q && p->val != q->val) { p = p->next; q = q->next; }//while return p; }};
GitHub测试程序源码
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
- android中使用shape自定义图形
- 文章标题
- 论文eps图的画法和问题
- linux学习基础---linux文件系统结构
- POI操作Excel设置前景色背景色
- LeetCode (160) Intersection of Two Linked Lists
- Source Insight简易教程(自己收藏)
- WebView loadUrl()加载页面
- POJ 2965
- oracle触发器
- 用一个消息队列(System V)实现客户端-服务器端
- oracle sql常用语句
- 我的阅读书单
- 《C++ Primer》学习笔记共享