(LeetCode)两个链表的第一个公共节点
2024-09-07 09:48:05
LeetCode上面的题目例如以下:
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
我的解决方法例如以下:
/**
* 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) {
int lengthA = 0,lengthB = 0;
for(ListNode head= headA;head!=null;head = head.next)
{
lengthA++;
}
for(ListNode head = headB;head!=null;head = head.next)
{
lengthB++;
}
if(lengthA>=lengthB)
{
for(int i=0;i<lengthA-lengthB;i++)
{
headA = headA.next;
}
}
else
{
for(int i=0;i<lengthB-lengthA;i++)
{
headB = headB.next;
}
}
for(ListNode newA =headA,newB = headB;newA!=null&&newB!=null;newA = newA.next,newB = newB.next)
{
if(newA==newB)
{
return newA;
}
}
return null;
}
}
* 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) {
int lengthA = 0,lengthB = 0;
for(ListNode head= headA;head!=null;head = head.next)
{
lengthA++;
}
for(ListNode head = headB;head!=null;head = head.next)
{
lengthB++;
}
if(lengthA>=lengthB)
{
for(int i=0;i<lengthA-lengthB;i++)
{
headA = headA.next;
}
}
else
{
for(int i=0;i<lengthB-lengthA;i++)
{
headB = headB.next;
}
}
for(ListNode newA =headA,newB = headB;newA!=null&&newB!=null;newA = newA.next,newB = newB.next)
{
if(newA==newB)
{
return newA;
}
}
return null;
}
}
最新文章
- 在ASP.NET MVC 中获取当前URL、controller、action
- 神奇的VIM~转IBM
- KETTLE实现数据的删除和更新
- ural 1341. Device
- js原生捕鱼达人(一)
- boost::circular_buffer
- 【阿里云产品公测】结构化数据服务OTS之JavaSDK初体验
- Oracle创建触发器实现主键自增
- PDFium-PDF开源之旅(1)-初探代码下载编译
- Android的PackageManager的使用
- sqlalchemy相关知识
- POJ - 3666 Making the Grade(dp+离散化)
- 中国天气网 JSON接口的城市编码解析及结果
- 【JMeter】生成报告-Dashboard Report
- OAF--基础
- centos7 mysql5.7安装
- 深度学习笔记(八)Focal Loss
- SQL 、NoSQL数据库教程
- Lecture 5
- django创建分页
热门文章
- 远程映射错误 “发生系统错误 1312 指定的登录会话不存在。可能已被终止 IIS 访问 远程共享目录”
- NKOI 1469 通向自由的钥匙
- css sticky footer 布局 手机端
- ++x和x++
- LeetCode OJ--Merge Intervals @
- HDU 6251 Inkopolis(2017 CCPC-Final,I题,环套树 + 结论)
- Codeforces Round #490 (Div. 3)
- Apollo 分布式配置中心
- protobuf3 语法解析
- eos智能合约执行流程