面试笔试杂项积累-leetcode 156-160

来源:互联网 发布:海康提示网络不可达 编辑:程序博客网 时间:2024/05/20 21:47

160.160-Intersection of Two Linked Lists-Difficulty: Easy

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, returnnull.
  • 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.

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

Subscribe to see which companies asked this question


思路

两个链表指向一个链表,找到汇聚的起点

解题思路:1.首先想到的是哈希,先将一个链表中结点都插入字典中,然后遍历另一个链表中的结点看是否有结点在字典中;但这种方法需要开辟较大的内存空间来存储字典;

2.双指针法.首先对其中一个链表头尾连接.那么问题就变成了看另一个链表是否存在环的问题了.但这种方法改变了原本链表的结构,需要在最后对其还原;

3.先计算两个链表的长度差,然后对长链表头结点开始移动长度差长的结点,找到位置对应的结点.然后逐个比较是否相等;

第二种方法就和之前的一道题一样,那就没有意义了

博主选择了最机智的第三种方法

/** * Definition for singly-linked list. * public class ListNode { *     public int val; *     public ListNode next; *     public ListNode(int x) { val = x; } * } */public class Solution {    public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {          ListNode A_temp = headA;        ListNode B_temp = headB;        int A_Length = 0;        int B_Length = 0;        while (A_temp != null || B_temp != null)        {            if (A_temp != null)            {                ++A_Length;                A_temp = A_temp.next;            }            if (B_temp != null)            {                ++B_Length;                B_temp = B_temp.next;            }        }        A_temp = headA;        B_temp = headB;        if (A_Length > B_Length)        {            for (int i = 0; i < A_Length - B_Length; i++)                A_temp = A_temp.next;        }        else if (B_Length > A_Length)        {            for (int i = 0; i < B_Length - A_Length; i++)                B_temp = B_temp.next;        }        while (A_temp != null)        {            if (A_temp == B_temp)                return A_temp;                         A_temp = A_temp.next;            B_temp = B_temp.next;        }        return null;    }}










1 0