您的位置:首页 > 健康 > 养生 > 长春火车站是哪个站_一站式装修公司有哪些_搜索量排名_网站制作出名的公司

长春火车站是哪个站_一站式装修公司有哪些_搜索量排名_网站制作出名的公司

2025/3/30 10:41:53 来源:https://blog.csdn.net/zhouky1993/article/details/146411203  浏览:    关键词:长春火车站是哪个站_一站式装修公司有哪些_搜索量排名_网站制作出名的公司
长春火车站是哪个站_一站式装修公司有哪些_搜索量排名_网站制作出名的公司

题目:找到两个相交列表的起始点,如图c1开始为A和B两个链表的相交点

举例1:8为两个链表的相交点。 注意:相交不止是数值上的相同。

举例2:2为相交点

举例3:没有相交点

解题思路:

相交证明最后一段链表路径完全一样,所以我利用栈先进后出的特性,把两个链表都放入栈中,然后将其相同部分放入一个新的栈中,遇到不一样的节点就结束循环。 最后从新的栈后进先出的原理,重新取到相交点的起初节点及完整路径。

/*** 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) {//将链表A与B分别放入栈A与B中Stack<ListNode> stackA = new Stack<>();while (headA != null) {stackA.push(headA);headA = headA.next;}Stack<ListNode> stackB = new Stack<>();while (headB != null) {stackB.push(headB);headB = headB.next;}//从链表的最后一个位置开始比较相同节点,相同的话放入新的栈中,不同的话结束比较Stack<ListNode> intersectStack = new Stack<>();while (!stackA.isEmpty() && !stackB.isEmpty()) {ListNode currectA = stackA.pop();ListNode currectB = stackB.pop();if (currectA == currectB) {intersectStack.push(currectA);} else {break;}}//将相交栈中的数据取出,重新拼成链表if (intersectStack.isEmpty()) {return null;}ListNode newHead = intersectStack.pop();ListNode currect = newHead;while (!intersectStack.isEmpty()) {currect.next = intersectStack.pop();currect = currect.next;}currect.next = null;return newHead;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com