题目描述:
题目分析:
这道题从表面上看我们应该从头到尾进行,但是仔细分析题目不难发现,两条链相交节点之前的节点数并不相同,因此无法进行遍历比较。这是后我们不难想到可以从尾部出发,但这是一条单链表,我们该如何从尾部向前进行遍历呢???不难想到一个数据结构,那就是栈,它具有先进后出的性质,我们可以遍历单链表,然后压栈,这样我们就拥有了两个倒序的链表栈顺序了,再掐准比较两个链表相交节点的情况,可以很容易就得出相交的节点了。
代码:
import java.util.Stack;
public class IntersectionNode {
public static void main(String[] args) {
// ListNode c1 = new ListNode(8);
// c1.next = new ListNode(4);
// c1.next.next = new ListNode(5);
//
// ListNode headA = new ListNode(4);
// headA.next = new ListNode(1);
// headA.next.next = c1;
//
// ListNode headB = new ListNode(5);
// headB.next = new ListNode(0);
// headB.next.next = new ListNode(1);
// headB.next.next.next = c1;
ListNode c2 = new ListNode(1);
ListNode headA = c2;
ListNode headB = c2;
System.out.println(getIntersectionNode(headA,headB).val);
}
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null){
return null;
}
Stack<ListNode> nodesA = new Stack<>();//分别用两个栈存储两条链,因为栈具有先进后出的作用
Stack<ListNode> nodesB = new Stack<>();
ListNode p = headA; //遍历A链的指针
ListNode q = headB; //遍历B链的指针
ListNode interNode = null; //申请一个空的相交节点变量
while (p!=null){ //遍历A链入栈
nodesA.push(p);
p = p.next;
}
while (q!=null){
nodesB.push(q); //遍历B链入栈
q = q.next;
}
while ((!nodesA.isEmpty()&&!nodesB.isEmpty())&&(nodesA.peek()==nodesB.peek())){
interNode = nodesA.pop();
nodesB.pop();
}
return interNode;
}
}