码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode 160] Intersection of Two Linked Lists

时间:2015-03-22 09:19:40      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   算法   查找   遍历   

题目链接:intersection-of-two-linked-lists


/**
 * 
		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.
 *
 */

public class IntersectionOfTwoLinkedLists {

	 public class ListNode {
		      int val;
		      ListNode next;
		      ListNode(int x) {
		          val = x;
		          next = null;
		      }
		  }
	 
//	 42 / 42 test cases passed.
//	 Status: Accepted
//	 Runtime: 327 ms
//	 Submitted: 3 minutes ago
	 
	 //时间复杂度 O(m+n)  空间复杂度 O(1)
	 
	 //解题思路:
	 //		1.先分别遍历统计两个链表的节点数。
	 //		2.然后再次遍历,这次让节点数较大的那个链表先走|两节点数值之差|步
	 //		3.最后同时遍历,判断节点是否相等
	 
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        
    	int numA = 0;	//	A链表的节点数
    	int numB = 0;	//	B链表的节点数
    	ListNode curA = headA;
    	ListNode curB = headB;
    	
		while (curA != null) {
			numA++;
			curA = curA.next;
		}
		while (curB != null) {
			numB++;
			curB = curB.next;
		}
		
		curA = headA;
		curB = headB;		
		while(numA < numB) {
			curB = curB.next;
			numB --;
		}
		while(numA > numB) {
			curA = curA.next;
			numA --;
		}
    	
		while(curA != curB) {
			curA = curA.next;
			curB = curB.next;
		}		
    	return curA;
    	
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


[LeetCode 160] Intersection of Two Linked Lists

标签:java   leetcode   算法   查找   遍历   

原文地址:http://blog.csdn.net/ever223/article/details/44519735

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!