160. Intersection of Two Linked Lists
来源:互联网 发布:奥迪工程师软件 编辑:程序博客网 时间:2024/06/06 19:42
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.
直接记住就可以,没什么技巧!
java
/** * 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; } int lenA = Length(headA); int lenB = Lenght(headB); while (lenA > lenB) { headA = headA.next; lenA--; } while (lenA < lenB) { headB = headB.next; lenB--; } while (headA != headB) { headA = headA.next; headB = headB.next; } return headA; } private int Length(ListNode head) { int num = 0; while (head != null) { head = head.next; num++; } return num; }}
python
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if headA is None or headB is None: return None lenA = self.length(headA) lenB = self.length(headB) while lenA > lenB: headA = headA.next lenA -= 1 while lenA < lenB: headB = headB.next lenB -= 1 while headA is not headB: headA = headA.next headB = headB.next return headA def length(self, head): num = 0 while head is not None: head = head.next num += 1 return num
阅读全文
0 0
- [LeetCode]160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160.Intersection of Two Linked Lists
- [leetcode] 160.Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 【LeetCode】160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 测试文章发送C
- 10月10 日c语言 构造5*5的二维数组,使主对角线的数字为1
- Linux系统基本命令行操作(五)
- Spring中引入多个properties文件的简易方法
- 【CentOS学习】一、win10+CentOS7.1双系统恢复引导
- 160. Intersection of Two Linked Lists
- datastage服务的停止与启动
- s3c2440的时钟体系
- 整合struts和spring时
- android开发中应用在桌面上的标识名称不见的解决
- Support Vector Machine
- 软件测试基础(一)
- 远程从Mongodb 数据库导出数据为json文件
- TensorFlow教程:TensorFlow实现多层感知机