Solution 7: 判断两链表是否相交
生活随笔
收集整理的這篇文章主要介紹了
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: 判断两链表是否相交的全部內容,希望文章能夠幫你解決所遇到的問題。