日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Solution 7: 判断两链表是否相交

發布時間:2023/12/9 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Solution 7: 判断两链表是否相交 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題描述

RT.

?

解決思路

(1)?兩鏈表都是單向鏈表:判斷兩鏈表的末尾節點是否相同;

(2)?兩鏈表中一個有環,一個沒環:不可能相交;

(3)?兩鏈表都有環:slow-fast雙指針方法。

?

程序

?

public class ListIntersection {// two single listpublic boolean isIntersectionOfTwoSingleList(ListNode l1, ListNode l2) {if (l1 == null || l2 == null) {return false;}// whether the end of two list is sameListNode endOfList1 = getEndOfList(l1);ListNode endOfList2 = getEndOfList(l2);return endOfList1 == endOfList2;}private ListNode getEndOfList(ListNode head) {if (head == null) {return null;}ListNode node = head;while (node.next != null) {node = node.next;}return node;}// two list with cyclepublic boolean isIntersectionOfTwoListWithCycle(ListNode l1, ListNode l2) {if (l1 == null || l2 == null) {return false;}ListNode slow = l1, fast = l2;while (fast.next != null || fast != null || slow != null) {slow = slow.next;fast = fast.next.next;if (slow == fast) {return true;}}return false;} }

?

Follow?up

求出兩個鏈表相交的第一個節點(如果存在的話)。

?

(1)?兩條單鏈表

a. 求出兩條鏈表的長度及長度之差diff,然后設立兩個指針指向兩鏈表的頭結點,其中指向長鏈表頭結點的指針向前移動diff步;

b. 然后同時移動兩指針,直到所指節點相同(地址相同)為止,否則返回null。

?

(2)?兩條鏈表有環

首先slow-fast,直到相遇為止,其中任意一個指針指回其頭結點,然后slow和fast指針同時移動,直到相遇,相遇的節點為第一個相交的節點。

(注意:可能有兩個相交的節點)

?

程序

public class ListIntersection2 {// two single listpublic ListNode getFirstIntersectionNodeOfSingleList(ListNode l1,ListNode l2) {ListNode longNode = l1, shortNode = l2;int len1 = getLenOfList(l1);int len2 = getLenOfList(l2);if (len1 < len2) {longNode = l2;shortNode = l1;}int diff = Math.abs(len1 - len2);// long move diff stepswhile (diff > 0) {longNode = longNode.next;--diff;}while (longNode != null && shortNode != null) {if (longNode == shortNode) {return longNode;}longNode = longNode.next;shortNode = shortNode.next;}return null;}private int getLenOfList(ListNode head) {ListNode node = head;int len = 0;while (node != null) {++len;node = node.next;}return len;}// two list with cyclepublic ListNode getFirstIntersectionNodeOfCycleList(ListNode l1, ListNode l2) {if (l1 == null || l2 == null) {return null;}ListNode slow = l1, fast = l2;while (fast.next != null || fast != null || slow != null) {if (fast == slow) {break;}slow = slow.next;fast = fast.next.next;}if (fast == null || slow == null) {return null;}slow = l1;while (slow != fast) {slow = slow.next;fast = fast.next;}return slow;} }

?

轉載于:https://www.cnblogs.com/harrygogo/p/4614277.html

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的Solution 7: 判断两链表是否相交的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。