两个链表的第一个公共结点

题目描述:输入两个链表,找出它们的第一个公共结点。

实现语言:Java

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.Stack;
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1==null||pHead2==null){
            return null;
        }
        Stack<ListNode> stk1=new Stack<ListNode>();
        Stack<ListNode> stk2=new Stack<ListNode>();
        while(pHead1!=null){
            stk1.push(pHead1);
            pHead1=pHead1.next;
        }
        while(pHead2!=null){
            stk2.push(pHead2);
            pHead2=pHead2.next;
        }
        ListNode commonNode=null;
        while(!stk1.isEmpty()&&!stk2.isEmpty()&&stk1.peek()==stk2.peek()){
            stk1.pop();
            commonNode=stk2.pop();
        }
        return commonNode;
    }
}

 实现语言:Java

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.HashMap;
public class Solution {
    public ListNode FindFirstCommonNode(ListNode head1, ListNode head2) {
        if(head1==null||head2==null){
            return null;
        }
        HashMap<ListNode,ListNode> map=new HashMap<ListNode,ListNode>();
        while(head1!=null){
            map.put(head1,head1);
            head1=head1.next;
        }
        while(head2!=null){
            if(map.containsKey(head2)){
                return head2;
            }
            head2=head2.next;
        }
        return null;
    }
}

实现语言:Java

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1==null||pHead2==null){
            return null;
        }
        ListNode cur=pHead1;
        int n=0;
        while(cur!=null){
            ++n;
            cur=cur.next;
        }
        cur=pHead2;
        while(cur!=null){
            --n;
            cur=cur.next;
        }
        ListNode shortList=null;
        ListNode longList=null;
        if(n<0){
            shortList=pHead1;
            longList=pHead2;
        }else{
            shortList=pHead2;
            longList=pHead1;
        }
        n=n<0?-n:n;
        for(int i=0;i<n;++i){
            longList=longList.next;
        }
        while(shortList!=null&&longList!=null&&shortList.val!=longList.val){
            shortList=shortList.next;
            longList=longList.next;
        }
        return longList;
    }
}

 

posted on 2018-12-30 10:36  lina2014  阅读(145)  评论(0编辑  收藏  举报

导航