leetcode121,LeetCode(160): Intersection of Two Linked Lists

 2023-11-22 阅读 33 评论 0

摘要:Intersection of Two Linked Lists: 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 leetcode121,begin to intersect at

Intersection of Two Linked Lists:

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

leetcode121,begin to intersect at node c1.

題意:找出給定的兩個鏈表,鏈表開始相交的交點。

思路:先分別遍歷兩個鏈表獲取兩個鏈表的長度,len1和len1,并定義兩個指針p和q,如果len1==len2則兩個指針分別同時指向鏈表的首節點;如果len1>len2或len1<len2,則指針p或q,指向第|len1-len2|個節點,然后在進行判斷。

代碼:

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {int a_len = 0;int b_len = 0;ListNode p = headA;ListNode q = headB;while(p!=null){a_len++;p=p.next;}p = headB;while(p!=null){b_len++;p=p.next;}if(a_len==0||b_len==0){return null;}p = headA;q = headB;int sub_len = a_len - b_len;if(sub_len!=0){if(sub_len>0){while(sub_len>0){p = p.next;sub_len --;}}else{sub_len = -1*sub_len;while(sub_len>0){q= q.next;sub_len--;}}}while(p!=null&&q!=null){if(p==q){return p;}else{p = p.next;q = q.next;}}return null;}

leetcode394。轉載于:https://www.cnblogs.com/Lewisr/p/5131454.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/184594.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息