《剑指offer》两个链表的第一个公共节点

来源:互联网 发布:网络爬虫软件下载 编辑:程序博客网 时间:2024/05/18 03:13

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

解析:暴力更直接。直接遍历两个链表分别存储到list1、list2,然后在list1和list2中找公共节点就好了

/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/import java.util.ArrayList;import java.util.List;public class Solution {    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {        if(pHead1==null||pHead2==null){//其中一条链表为空,当然没有公共节点了            return null;        }        List<ListNode> list1 = new ArrayList<>();//存第1个链表的节点        List<ListNode> list2 = new ArrayList<>();//存第2个链表的节点        while (pHead1!=null){            list1.add(pHead1);            pHead1=pHead1.next;        }        while (pHead2!=null){            list2.add(pHead2);            pHead2=pHead2.next;        }        for(ListNode node1:list1){            for(ListNode node2:list2){                if(node2.val==node1.val){//找到了公共节点就返回了                    return node2;                }            }        }        return null;    }}
阅读全文
0 0
原创粉丝点击