java——單鏈表的交
阿新 • • 發佈:2018-12-17
單鏈表的交:
/** * 建立交點 * @param t1 * @param t2 */ public static void CreateCut(Node t1,Node t2) { Entry head1 = t1.head; Entry head2 = t2.head; head1.next.next = head2.next; } /** * 判斷是否相交 * @param t1 * @param t2 * @return */ public static boolean isCut(Node t1,Node t2) { Node.Entry head1 = t1.head; //獲得兩個連結串列的頭結點 Node.Entry head2 = t2.head; int len1 = t1.getLength(); //獲取到兩個連結串列長度 int len2 = t2.getLength(); int mylen = len1-len2; //找到兩個連結串列的差值 if(mylen<0) { //如果mylen小於0代表t2比t1長 head1 = t2.head; //此時換一下位置即可,保證head1為最長元素的頭結點 head2 = t1.head; } for (int i = 0; i <mylen; i++) { //對長的先進行遍歷 head1 = head1.next; } //進行迴圈,直到兩個連結串列找到交點,或者遍歷完成 while(head1 != null && head2 != null && head1 != head2) { head1 = head1.next; head2 = head2.next; } //如果找到交點 返回true 負責為false if(head1 == head2 && head1 != null && head2 != null) { return true; } else { return false; } } /** * 找到交點 * @param t1 * @param t2 * @return */ public static int isCutPoint(Node t1,Node t2) { Node.Entry head1 = t1.head; Node.Entry head2 = t2.head; int len1 = t1.getLength(); int len2 = t2.getLength(); int mylen = len1-len2; if(mylen<0) { head1 = t2.head; head2 = t1.head; } for (int i = 0; i <mylen; i++) { head1 = head1.next; } while(head1 !=null && head2 !=null && head1 != head2) { head1 = head1.next; head2 = head2.next; } if(head1 == head2 && head1 !=null && head2 != null){ return head1.data; } else { return -1; } }