前言
11.3号打卡,大家如果想参与活动领书籍的,去当天的另一篇文章,按照格式回答问题,留言被精选即算打卡生效。
题目
leetcode160-相交链表
中文链接:
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
英文链接:
https://leetcode.com/problems/intersection-of-two-linked-lists/
题目详述
编写一个程序,找到两个单链表相交的起始节点。
例如,下面的两个链表:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
在节点 c1 开始相交。
注意:
如果两个链表没有交点,返回
null
.在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
题目详解
思路
如果两个链表有共同的节点,那么就是可以先分别计算两个链表的长度。
两个链表是A和B,如果A的·长度比B的长,长度差是C,那么A就先从头结点走个长度差C,这样两者的长度就一样长了;
然后两者一起进行遍历,直到找到的节点是相同的节点,那么循环结束,找到这个节点,返回即可。
代码
1/**
2 * Definition for singly-linked list.
3 * public class ListNode {
4 * int val;
5 * ListNode next;
6 * ListNode(int x) {
7 * val = x;
8 * next = null;
9 * }
10 * }
11 */
12public class Solution {
13 public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
14 int lengthA = 0;
15 int lengthB = 0;
16 ListNode tempA = headA;
17 ListNode tempB = headB;
18 while(tempA != null)
19 {
20 lengthA++;
21 tempA = tempA.next;
22 }
23 while(tempB != null)
24 {
25 lengthB++;
26 tempB = tempB.next;
27 }
28 tempA = headA;
29 tempB = headB;
30 if(lengthB > lengthA)
31 {
32 int cha = lengthB - lengthA;
33 for(int i=0;i<cha&&tempB != null;i++)
34 tempB = tempB.next;
35 }else{
36 int cha = lengthA - lengthB;
37 for(int i=0;i<cha&&tempA != null;i++)
38 tempA = tempA.next;
39 }
40 while(tempA != null && tempB != null && tempA != tempB)
41 {
42 tempA = tempA.next;
43 tempB = tempB.next;
44 }
45 return tempA;
46 }
47}
代码讲解
18到27行,去求A和B链表的长度;
30-39行,A与B那个长度长,如果B长度长,那么B就去先走长度差,直到B与A的长度一样,如果A长度长也同理
40行到44行,A与B一起遍历,直到找到相同的节点,然后输出
结束语
2018.11.3打卡。
END
推荐阅读
每天一道leetcode154-寻找旋转排序数组(有重复数字)中的最小值
扫一扫
有3T编程资料等你来拿