52 两个链表中的第一个公共节点

package sort;

import java.util.Stack;

public class Test52 {

    public static void main(String[] args) {
        ListNode a = new ListNode(1);
        ListNode b = new ListNode(2);
        ListNode c = new ListNode(3);
        ListNode d = new ListNode(4);
        ListNode e = new ListNode(5);
        ListNode f = new ListNode(6);
        ListNode g = new ListNode(7);
        // 第一个List
        a.next = b;
        b.next = c;
        c.next = f;
        f.next = g;
        // 第二个List
        d.next = e;
        e.next = f;
        f.next = g;
        System.out.println(function(a, d).date);

    }

    public static ListNode function(ListNode list1, ListNode list2) {
        Stack<ListNode> stack1 = new Stack<ListNode>();
        Stack<ListNode> stack2 = new Stack<ListNode>();
        while (list1 != null) {
            stack1.push(list1);
            list1 = list1.next;
        }

        while (list2 != null) {
            stack2.push(list2);
            list2 = list2.next;
        }
        while (!stack1.isEmpty() && !stack2.isEmpty()
                && stack1.peek() == stack2.peek()) {

            stack1.pop();
            stack2.pop();
        }

        return stack1.peek().next;

    }

    public static ListNode function2(ListNode list1, ListNode list2) {

        int length1 = 0;
        int length2 = 0;
        int cha = 0;
        ListNode temp = list1;
        while (temp != null) {
            length1++;
            temp = temp.next;
        }
        temp = list2;

        while (temp != null) {
            length2++;
            temp = temp.next;
        }

        if (length1 > length2) {
            cha = length1 - length2;
            for (int i = 0; i < cha; i++) {
                list1 = list1.next;
            }
            while (list1 != null && list2 != null && list1 != list2) {
                list1 = list1.next;
                list2 = list2.next;
            }
        } else {

            cha = length2 - length1;
            for (int i = 0; i < cha; i++) {
                list2 = list2.next;
            }
            while (list1 != null && list2 != null && list1 != list2) {
                list1 = list1.next;
                list2 = list2.next;
            }

        }

        return list2;

    }

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值