Intersection of Two Linked Lists
来源:互联网 发布:mac 列出文件路径 命令 编辑:程序博客网 时间:2024/05/17 03:24
Description:
Write a program to find the node at which the intersection of two singly linked lists begins.
问题描述:
写一个函数,返回两条链表交集链表的头结点。
限制:
- 整条链表中均无环
- 时间复杂度O(n),空间复杂度O(1)
解法一(迭代)
思路:两次迭代操作,假设有A和B两条链表,对于每个链表每次遍历到末尾就将另一条链表的头结点赋给它。对于A完成(a+c)次遍历后,最多还要进行(b+c)次遍历。对于B完成(b+c)次遍历后,最多还要进行(a+c)次遍历。其中c为两条链表的交集。那么A完成(a+c+b)次遍历和B完成(b+c+a)次遍历,两个结点就相遇了(返回交集链表的头结点,任一结点均可)
Code:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null) return null; ListNode a = headA; ListNode b = headB; while(a != b){ a = a == null ? headB : a.next; b = b == null ? headA : b.next; } return a; }}
0 0
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- uCOS-II任务间通信之全局变量 [转载]
- 二叉树题目整理
- Windows 10 下Maven的系统环境变量,
- 模拟实现strcpy函数
- centos 7 安装Google earth
- Intersection of Two Linked Lists
- [NOIP2016] 愤怒的小鸟
- JAVA中堆和栈的区别
- 欢迎使用CSDN-markdown编辑器
- 生产
- 企业虚拟化的目的及本质
- Java中时间的比较总结
- js结合拍php建立倒计时功能(一个页面一个或者多个)
- HDU 2177 —— 取(2堆)石子游戏