1. 程式人生 > >java判斷兩個單鏈表是否相交

java判斷兩個單鏈表是否相交

fast n) detail 無環 etl ++ code 數據 enter

轉載於:http://blog.csdn.net/happymatilian/article/details/47811161

思路:

鏈表分有環鏈表和無環鏈表,如果兩個鏈表存在相交,則只有兩種可能,兩個鏈表都無環或者都有環。

(1)如果鏈表都無環,則先判斷鏈表的尾指針是否一樣,如果不一樣,則沒有相交。如果一樣,則找出兩個鏈表的長度差,將兩個鏈表從距離尾節點同樣的距離進行掃描,如果相交,則必然有一處掃描節點相同。實例數據List1:1->2->3->4->5->6->7->null,List2:0->9->8->6->7->null,第一個相交節點為6

示例圖如下,

技術分享

(2)如果鏈表都有環,則只肯能有下面兩種情況(如下圖)。兩種情況區分的方法為:入環點是否相同。

如果相同則為第一種情況:那麽查找第一個相交點與無環的單鏈表相交找第一個交點的方法一樣。

如果入環點不同,則為第二種情況,這個相交點或者為list1 的入環點loop1或者為list2的入環點loop2。

情況1實例數據(List1:1->2->3->4->5->6->7->4,List2:0->9->8->2->3->4->5->6->7->4,第一個交點為2)

情況2實例數據(List1:1->2->3->4->5->6->7->4,List2:0->9->8->6->7->4->5->6,第一個交點為4或6)

技術分享 技術分享

public static class Node {  
        public int value;  
        public Node next;  
  
        public Node(int data) {  
            this.value = data;  
        }  
    }  
/*判斷是否相交,如果相交,得到第一個相交點*/ public static Node getIntersectNode(Node head1, Node head2) { if (head1 == null || head2 == null) { return null; } Node loop1 = getLoopNode(head1); Node loop2 = getLoopNode(head2); if (loop1 == null && loop2 == null) { return noLoop(head1, head2); } if (loop1 != null && loop2 != null) { return bothLoop(head1, loop1, head2, loop2); } return null; } /* * 判斷是否存在環,如果存在,則找出環的入口點。 * 入口點找法:快慢指針,塊指針走兩步,滿指針走一步,如果存在循環,則在慢指針走完環前,總會和快指針相遇。 * 從頭指針和相遇點同時向後走,相遇的點必定是入口點。*/ public static Node getLoopNode(Node head) { if (head == null || head.next == null || head.next.next == null) { return null; } Node n1 = head.next; // n1 -> slow Node n2 = head.next.next; // n2 -> fast while (n1 != n2) { if (n2.next == null || n2.next.next == null) { return null; } n2 = n2.next.next; n1 = n1.next; } n2 = head; // n2 -> walk again from head while (n1 != n2) { n1 = n1.next; n2 = n2.next; } return n1; } /*無環時的判斷方法*/ public static Node noLoop(Node head1, Node head2) { if (head1 == null || head2 == null) { return null; } Node cur1 = head1; Node cur2 = head2; int n = 0; while (cur1.next != null) { n++; cur1 = cur1.next; } while (cur2.next != null) { n--; cur2 = cur2.next; } if (cur1 != cur2) { return null; } cur1 = n > 0 ? head1 : head2; cur2 = cur1 == head1 ? head2 : head1; n = Math.abs(n); while (n != 0) { n--; cur1 = cur1.next; } while (cur1 != cur2) { cur1 = cur1.next; cur2 = cur2.next; } return cur1; } /*有環時的判斷方法*/ [java] view plain copy public static Node bothLoop(Node head1, Node loop1, Node head2, Node loop2) { Node cur1 = null; Node cur2 = null; if (loop1 == loop2) { cur1 = head1; cur2 = head2; int n = 0; while (cur1 != loop1) { n++; cur1 = cur1.next; } while (cur2 != loop2) { n--; cur2 = cur2.next; } cur1 = n > 0 ? head1 : head2; cur2 = cur1 == head1 ? head2 : head1; n = Math.abs(n); while (n != 0) { n--; cur1 = cur1.next; } while (cur1 != cur2) { cur1 = cur1.next; cur2 = cur2.next; } return cur1; } else { cur1 = loop1.next; while (cur1 != loop1) { if (cur1 == loop2) { return loop1; } cur1 = cur1.next; } return null; } }

java判斷兩個單鏈表是否相交