Intersection of Two Linked Lists
来源:互联网 发布:opera 10.10 linux 编辑:程序博客网 时间:2024/05/12 20:07
/* Write a program to find the node at which* the intersection of two singly linked lists begins.* This solution runs O(n) time.** Basic idea:* 1. Traverse the two linked list to find length M and N;* 2. Get back to the heads, the skip |M - N| nodes on the longer list;* 3. Now walk through both lists together until you find the common node.** Important notes:* When submitting to leetcode, the debug info* System.out.println() should be commented,* since it is very time consuming!*/ public class Solution {public ListNode getIntersectionNode(ListNodeheadA, ListNode headB) { /* My answer starts here */ListNode ptrA= headA;ListNode ptrB= headB;int lengthA= 0;int lengthB= 0;int i; // get the length of list Awhile (null!= ptrA) {//System.out.println("ptrA: " + ptrA.val);lengthA++;ptrA = ptrA.next;}ptrA = headA;// pointer back to the head // get the length of list Bwhile (null!= ptrB) {//System.out.println("ptrB: " + ptrB.val);lengthB++;ptrB = ptrB.next;}ptrB = headB;// pointer back to the head // skip the first |M - N| nodes of the longer listif (lengthA>= lengthB) {for (i = 0; i < lengthA - lengthB; i++) {ptrA = ptrA.next;}} else {for (i = 0; i < lengthB - lengthA; i++) {ptrB = ptrB.next;}} // compare one by one of the remaining nodeswhile (null!= ptrA) {if (ptrA.val== ptrB.val) {return ptrA;// find the intersection}ptrA = ptrA.next;ptrB = ptrB.next;}return null; // no intersection /* My answer ends here */}}
0 0
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- tomcat发布在根目录下
- 如何设置 Base SDK 和 iOS Deployment Target
- 每个程序员都应该读的非编程书
- j2EE学习路线
- unity3D 教程宝典之GL
- Intersection of Two Linked Lists
- 做程序员的目的是什么那? 最终目的? 改变世界?钱?
- 量化交易入门
- hihocoder #1084 (后缀数组求模糊匹配)
- 第一次写博客
- Pdb调试的常见操作
- Java 多线程 join和interrupt 方法
- 啊哈!i'm coming!
- 2014省机器人比赛总结