LeetCode#160.Intersection of Two Linked Lists
来源:互联网 发布:量子 知乎 编辑:程序博客网 时间:2024/06/10 11:41
- 题目:求两个链表相交的起始节点
- 难度:Easy
- 思路:(1)求出两个链表的长度,让长的链表先走n步(两个链表长度的差),然后两个链表同时走;(2)如果两个链表相交,经过两趟循环遍历就能找到交点,第一次遍历后,将节点指向另一个链表的头
- 代码:
方法一:
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null){ return null; } int len1 = 1; int len2 = 1; ListNode node1 = headA; ListNode node2 = headB; //求出第一个链表的长度 while(node1.next != null){ node1 = node1.next; len1++; } //求出第二个链表的长度 while(node2.next != null){ node2 = node2.next; len2++; } //如果两个链表的尾不相同的话,则说明链表不会相交 if(node1 != node2){ return null; } //headA先走len1 - len2步 if(len1 > len2){ for(int i = 0; i < len1 - len2; i++){ headA = headA.next; } }else{ for(int i = 0; i < len2 - len1; i++){ headB = headB.next; } } while(headA != headB){ headA = headA.next; headB = headB.next; } return headA; }
方法二:
public ListNode getIntersectionNode1(ListNode headA, ListNode headB) { //boundary check if(headA == null || headB == null) return null; ListNode a = headA; ListNode b = headB; //if a & b have different len, then we will stop the loop after second iteration while( a != b){ //for the end of first iteration, we just reset the pointer to the head of another linkedlist a = a == null? headB : a.next; b = b == null? headA : b.next; } return a; }
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 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
- 160.[Leetcode]Intersection of Two Linked Lists
- Codeforces #410(div2) B. Mike and strings (暴力枚举
- 积分系统(3)-详细公告页面之Controller层
- [BZOJ3451][Tyvj1953]Normal
- Captcha Cracker
- Leetcode-标签为Tree 543. Diameter of Binary Tree
- LeetCode#160.Intersection of Two Linked Lists
- innerHTML使用入门
- 关于JDBC中的Mysql驱动所遇到的坑
- 逆向工程核心原理学习笔记(四):检索API方法2-设置断点
- ssh 事务不能回滚的问题总结
- 1分钟实现“延迟消息”功能
- 【数据结构】数组、链表、栈、队列、二叉树
- Python的神奇一行代码
- JavaScript如何把选中d的节点添加到左边或右边