LeetCode OJ 之 Intersection of Two Linked Lists (两个链表的交点)
来源:互联网 发布:银行家算法安全性算法 编辑:程序博客网 时间:2024/05/29 05:56
题目:
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.(时间复杂度要求O(n),空间复杂度O(1))
思路:
长的链表先多走 (len1 - len2)步,然后和短链表同步往下走,遇到的第一个相同的节点就是第一个交点。
代码:
/** * 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) { ListNode *qa = headA; ListNode *qb = headB; int lena = 0;//链表headA的长度 int lenb = 0;//链表headB的长度 while(qa) { lena++; qa = qa->next; } while(qb) { lenb++; qb = qb->next; } int gap = lena > lenb ? lena - lenb : lenb - lena ; //使qa指向长链表,qb指向短链表 if(lena > lenb) { qa = headA; qb = headB; } else { qa = headB; qb = headA; } //qa先走gap步 for(int i = 0 ; i < gap ; i++) { qa = qa->next; } //qa和qb再同时遍历,直到遇到相等的结点或者链表结束 while(qa && qb && qa->val != qb->val) { qa = qa->next; qb = qb->next; } return qa; }};
0 0
- LeetCode OJ 之 Intersection of Two Linked Lists (两个链表的交点)
- LeetCode--Intersection of Two Linked Lists (两个链表的交点)Python
- 160 Intersection of Two Linked Lists 求两个链表的交点
- leetcode解题之160# Intersection of Two Linked Lists Java版 (两个链表的第一个公共结点)
- LeetCode OJ Intersection of Two Linked Lists
- 【leetcode 两个链表的交集点】Intersection of Two Linked Lists
- 【leetcode 两个链表的交集点】Intersection of Two Linked Lists
- [leetcode]Intersection of Two Linked Lists[java]找出两个链表的公共节点
- (LeetCode)Intersection of Two Linked Lists --- 两个链表的交集
- leetcode之Intersection of Two Linked Lists
- LeetCode之Intersection of Two Linked Lists
- LeetCode 之 Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- Leetcode之Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- Leetcode 之 Intersection of Two Linked Lists
- Intersection of Two Linked Lists 找出2个链表的交点
- 让照片导入苹果iphone手机相机胶卷,不用在电脑删除,直接在手机上删除照片图文教程
- Javadoc 执行后报告java.lang.NullPointerException问题求解
- 好文转载Apache Maven 入门篇(下)
- QTP自动化测试
- "><img src=1 onerror=alert(document.cookie)>
- LeetCode OJ 之 Intersection of Two Linked Lists (两个链表的交点)
- android HttpURLConnection
- eclipse coco2d 资源错误
- 用Xcode编写一个五子棋(还是一个初学者)
- "><img src=hi onerror=alert(1)>
- 好文转载
- 记录大学的点点滴滴。。。
- Java 1203 JDBC
- STP选举根桥、根端口、指定端口