Leetcode---相交链表--两种解法

相交链表

题目地址:相交链表
解法一

  • 利用set集合存储a链表的地址,再遍历b链表每个节点,碰到相等的
    就返回
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
		//解法一:
		if(headA==null||headB==null) {
			return null;
		}
		Set<ListNode> nodes = new HashSet<ListNode>();
		while(headA!=null) {
			nodes.add(headA);
			headA = headA .next;
		}
		while(headB!=null) {
			if(nodes.contains(headB)) {
				return headB;
			}
			headB = headB .next;
		}
		return null;
	}

解法二

  • 利用两个指针分别指向a,b的头,分别遍历a,b中所有不重复的节点,那么,两个指针走的长度肯定是相等的
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
		if(headA==null||headB==null) {
			return null;
		}
		ListNode a = headA,b = headB;
		while(a!=b) {
			a = a==null?headB:a.next;
			b = b==null?headA:b.next;
		}
		return a;
	}

猜你喜欢

转载自blog.csdn.net/tiaochewang219/article/details/84500690