兩個單向鏈表,找出它們的第一個公用結點

來源:互聯網
上載者:User
package structure.list;import structure.list.node.LNode_01;/** * 題目:兩個單向鏈表,找出它們的第一個公用結點 *  * @author Toy *  */public class First_CommonNode {LNode_01 head1 = null;LNode_01 head2 = null;LNode_01 head = null;public LNode_01 method_01() {init();return getFirstCommonNode_01(head1, head2);}/** * 逐個考察 O(m*n) *  * @param head1 * @param head2 * @return */private LNode_01 getFirstCommonNode_01(LNode_01 head1, LNode_01 head2) {LNode_01 p = head1;LNode_01 q = head2;while (p != null) {q = head2;while (q != null) {if (q == p) {return p;}q = q.next;}p = p.next;}return null;}public LNode_01 method_02() {return getFirstCommonNode_02(head1, head2);}/** * 先找到長度差K,然後長的先遍曆K步,二者再同步遍曆 *  * @param head1 * @param head2 * @return */private LNode_01 getFirstCommonNode_02(LNode_01 head1, LNode_01 head2) {int len1 = LinkList_01.getLength(head1);int len2 = LinkList_01.getLength(head2);int delta = Math.abs(len1 - len2);LNode_01 first = head1;LNode_01 follow = head2;if (len2 > len1) {first = head2;follow = head1;}first = LinkList_01.toNodeK(first, delta + 1);while (follow != null && first != null) {if (follow == first) {return follow;}follow = follow.next;first = first.next;}return null;}public void init() {head = creatList();head1 = creatList();head2 = creatList();head1 = concatList(head1, head);head2 = concatList(head2, head);}private LNode_01 creatList() {System.out.println("Creat new list");LinkList_01 list = new LinkList_01();list.header = null;list.creat();list.show();return list.header;}public LNode_01 concatList(LNode_01 head1, LNode_01 head) {LNode_01 p = head1;while (p.next != null) {p = p.next;}p.next = head;return head1;}/** * @param args */public static void main(String[] args) {First_CommonNode f = new First_CommonNode();LNode_01 n = f.method_01();if (n == null) {System.out.println("not find");} else {System.out.println("first common elem: " + n.data);}n = f.method_02();if (n == null) {System.out.println("not find");} else {System.out.println("first common elem: " + n.data);}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.