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./**
- 题目重叠的意思是后边的都得是相同的,光交叉相等一个是不行的(除了最后的节点),如果是单向链表,两个有公共结点而部分重合的链表,拓扑形状看起来像一个Y,而不可能像X。
- * Definition for singly-linked list.
- * public class ListNode {
- * int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int a=0,b=0,sub,i=0; //必须要初始化,这儿不初始化,下边也得要赋值,不然报错
ListNode nodeA=headA,nodeB=headB; //看,可以定义在同一行
if(headA==null || headB==null) return null;
else{
while(nodeA.next!=null){
nodeA=nodeA.next;
++a;
}
while(nodeB.next!=null){
nodeB=nodeB.next;
++b;
}
}
sub=a>=b? a-b : b-a; //可以使用Math.abs(a-b);
nodeA=a>=b? headA : headB;
nodeB=a>=b? headB : headA;
while(i<sub){
nodeA=nodeA.next;
++i;
}
while(nodeA!=nodeB){ //不错哦,如果一旦相等就返回
nodeA=nodeA.next;
nodeB=nodeB.next;
}
return nodeA; //包含了相等于不相等两种情况
}
}
思路一样,写法稍微有点差别:http://www.1point3acres.com/bbs/thread-110377-1-1.html
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
int lenA = length(headA);
int lenB = length(headB);
int diff = Math.abs(lenA - lenB);
while(diff > 0) {
if (lenA > lenB) headA = headA.next;
else headB = headB.next;
diff--;
}
while (headA != null && headB != null) {
if (headA.val == headB.val) return headA;
headA = headA.next;
headB = headB.next;
}
return null;
}
private int length(ListNode n) {
if (n == null) return 0;
int length = 0;
while (n != null) {
length++;
n = n.next;
}
return length;
}
}