剑指offer:两个链表的第一个公共结点

来源:互联网 发布:淘宝宝贝分类怎么链接 编辑:程序博客网 时间:2024/05/27 20:52

题目描述

输入两个链表,找出它们的第一个公共结点

用ArrayList的contains方法判断

【运行时间:27ms  占用内存:8660k】
先将pHead1的所有节点装入arraylist中,再遍历pHead2判断arraylist是否有pHead2后面的节点,如果有返回当前节点。否则返回null。
import java.util.*;public class Solution {    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ArrayList<ListNode> arraylist=new ArrayList<ListNode>();    while(pHead1!=null){    arraylist.add(pHead1);    pHead1=pHead1.next;    }        while(pHead2!=null){    if(arraylist.contains(pHead2)){    return pHead2;    }    pHead2=pHead2.next;    }        return null;}}

HashMap的containsKey方法

【运行时间:22ms  占用内存:8620k】
方法和用ArrayList一样
import java.util.*;public class Solution {    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { HashMap<ListNode,Integer> map=new HashMap<ListNode,Integer>();        while(pHead1!=null){            map.put(pHead1,0);            pHead1=pHead1.next;        }                while(pHead2!=null){            if(map.containsKey(pHead2))                return pHead2;            pHead2=pHead2.next;        }        return null;    }}

直接操作链表

两个链表相交有相同的尾节点,因此可以选出最长的那个链表,让它先走那个差值长度。然后两个链表再一起走,边走边判断。得到相同的节点,再返回,否则返回nulll。

【运行时间:23ms  占用内存:8652k】

/*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; int len1=getLen(pHead1);        int len2=getLen(pHead2);        if(len1>=len2){            pHead1=Step(pHead1,len1-len2);        }else{            pHead2=Step(pHead2,len2-len1);        }                while(pHead1!=null){            if(pHead1==pHead2){                return pHead1;            }            pHead1=pHead1.next;            pHead2=pHead2.next;        }        return null;    }        private int getLen(ListNode pHead){        if(pHead==null)return 0;        int count=0;        while(pHead!=null){            count++;            pHead=pHead.next;        }        return count;    }        private ListNode Step(ListNode pHead,int step){        while(step>0){            pHead=pHead.next;            step--;        }        return pHead;    }}



原创粉丝点击