zoukankan      html  css  js  c++  java
  • 剑指offer 36.时间空间效率的平衡 两个链表的第一个公共结点

    题目描述

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

    解题思路

    如果存在共同节点的话,那么从该节点,两个链表之后的元素都是相同的。
    也就是说两个链表从尾部往前到某个点,节点都是一样的。
    我们可以用两个栈分别来装这两条链表。一个一个比较出来的值。
    找到第一个相同的节点。

    代码如下

    public class FindFirstCommonNode {
        public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
            if (pHead1==null&&pHead2==null) {
                return null;
            }
            Stack<ListNode> stack1=new Stack<ListNode>();
            Stack<ListNode> stack2=new Stack<ListNode>();
            ListNode resultNode=null;
            while (pHead1!=null) {
                stack1.push(pHead1);
                pHead1=pHead1.next;
            }
            while (pHead2!=null) {
                stack2.push(pHead2);
                pHead2=pHead2.next;        
            }
            while (!stack1.isEmpty()&&!stack2.isEmpty()&&stack1.peek()==stack2.peek()) {
                stack2.pop();
                resultNode=stack1.pop();
            }
            return resultNode;
        }
        
        
        class ListNode {
            int val;
            ListNode next = null;
    
            ListNode(int val) {
                this.val = val;
            }
        }    
    }
  • 相关阅读:
    日志收集
    解决spawn-fcgi child exited with: 1
    confluence启动关闭
    Informatica 启动、停止工作流命令
    启动obiee
    oracle修改连接空闲自动断开
    ORA-00845: MEMORY_TARGET not supported on this system
    svn执行clean up命令时报错
    手游推广
    phonegap/cordova 升级版本
  • 原文地址:https://www.cnblogs.com/Transkai/p/11287030.html
Copyright © 2011-2022 走看看