输入两个链表,找出它们的第一个公共节点。
方法一:先将其中一个链表元素全部存到Map里,然后遍历另一个链表,同时检测Hash中是否存在当前结点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
class Solution {
ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
while(headA != null){
set.add(headA);
headA = headA.next;
}
while(headB != null){
if(set.contains(headB)){
return headB;
}
headB = headB.next;
}
return null;
}
}
方法二:栈是先进后出,所以可以将两个链表放入两个栈中,并同时进行出栈比较是否相等,如果相等就继续进行处长操作,如果不等则结束。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
class Solution {
ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Stack<ListNode> stack1 = new Stack();
Stack<ListNode> stack2 = new Stack();
while(headA != null){
stack1.push(headA);
headA = headA.next;
}
while(headB != null){
stack2.push(headB);
headB = headB.next;
}
ListNode preNode = null;
while(stack1.size() > 0 && stack2.size() > 0){
if(stack1.peek() == stack2.peek()){
preNode = stack1.pop();
stack2.pop();
}else{
break;
}
}
return preNode;
}
}
方法三:将链表进行拼接,A+B和B+A,这样两条链表的长度是相等的,如果有公共子节点则后几个节点相等,此时返回第一个相等的节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
class Solution {
ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null){
return null;
}
ListNode p1 = headA;
ListNode p2 = headB;
while(p1 != p2){
p1 = p1.next;
p2 = p2.next;
if(p1 != p2){
if(p1 == null){
p1 = headB;
}
if(p2 == null){
p2 = headA;
}
}
}
return p1;
}
}
方法四:由于两个链表最后几个节点是相等的,因此可以让长度较长的链表先走| l1 - l2 |个节点,再比较剩余节点与另一链表是否有公共节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
class Solution {
ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null){
return null;
}
ListNode p1 = headA;
ListNode p2 = headB;
int l1 = 0,l2 = 0;
while(p1 != null){
p1 = p1.next;
l1++;
}
while(p2 != null){
p2 = p2.next;
l2++;
}
p1 = headA;
p2 = headB;
int i = l1 > l2 ? l1 - l2 : l2 - l1;
if(l1 > l2){
int a = 0;
while(a < i){
a++;
p1 = p1.next;
}
}
if(l2 > l1){
int a = 0;
while(a < i){
a++;
p2 = p2.next;
}
}
while(p1 != p2){
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}