题目
输入两个链表,找出它们的第一个公共节点。
代码实现
遍历
思路:先遍历两个链表得到各自的长度,然后长的链表先遍历差值次,然后两个链表同时遍历,如果有公共节点一定能得到
/**
* 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 lenA = 0;
int lenB = 0;
ListNode tempA = headA,tempB = headB;
while (tempA != null){
lenA++;
tempA = tempA.next;
}
tempA = headA;
while (tempB!=null){
lenB++;
tempB = tempB.next;
}
tempB = headB;
while (lenA > lenB){
tempA = tempA.next;
lenA--;
}
while (lenB > lenA){
tempB = tempB.next;
lenB--;
}
while (tempA!=null){
if(tempA == tempB){
return tempA;
}
tempA = tempA.next;
tempB = tempB.next;
}
return null;
}
}
双指针
遍历两个链表,当到链表最后则从另一个链表开始继续遍历,
因为第二次遍历到公共节点的举例相同,最后一定能得到公共节点
/**
* 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) {
if (headA == null || headB == null){
return null;
}
ListNode nodeA = headA;
ListNode nodeB = headB;
int n = 0;
while (nodeA != nodeB && n < 3){
if (nodeA.next != null) {
nodeA = nodeA.next ;
}else {
nodeA = headB;
n++;
}
if(nodeB.next != null) {
nodeB = nodeB.next;
}else {
nodeB = headA;
n++;
}
}
return nodeA == nodeB ? nodeA : null;
}
}
大佬代码
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A = headA, B = headB;
while (A != B) {
A = A != null ? A.next : headB;
B = B != null ? B.next : headA;
}
return A;
}
}