zoukankan      html  css  js  c++  java
  • 160. 两个链表的相交点 Intersection of Two Linked Lists

    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.
    题意:找出两个两个链表的相交点
    解法:先算出两个链表的长度,同时遍历两个链表,较短的链表从位于Math.Abs(countA - countB)的节点开始遍历,直到两个指针指向的节点相同
    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * public int val;
    5. * public ListNode next;
    6. * public ListNode(int x) { val = x; }
    7. * }
    8. */
    9. public class Solution {
    10. public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {
    11. int countA = GetCount(headA);
    12. int countB = GetCount(headB);
    13. int offset = Math.Abs(countA - countB);
    14. if (countA > countB) {
    15. headA = GetIndex(headA, offset);
    16. } else {
    17. headB = GetIndex(headB, offset);
    18. }
    19. while (headA != null && headB!=null) {
    20. if (headA.GetHashCode() == headB.GetHashCode()) {
    21. return headA;
    22. } else {
    23. headA = headA.next;
    24. headB = headB.next;
    25. }
    26. }
    27. return null;
    28. }
    29. public ListNode GetIndex(ListNode head,int index) {
    30. int count = 0;
    31. ListNode node = head;
    32. while (node != null) {
    33. if (count == index) {
    34. return node;
    35. } else {
    36. count++;
    37. node = node.next;
    38. }
    39. }
    40. return null;
    41. }
    42. public int GetCount(ListNode head) {
    43. int count = 0;
    44. ListNode node = head;
    45. while (node != null) {
    46. count++;
    47. node = node.next;
    48. }
    49. return count;
    50. }
    51. }








  • 相关阅读:
    map按照值排序
    结构体的三种排序方式
    归并排序
    数组模拟双向链表
    二刷斐波那契高精度
    2019年9月训练(贰)区间DP (luogu 4290)
    2019年9月训练(壹)数位DP (HDU 2089)
    2019年8月训练(贰)
    2019年8月训练(壹)二分,三分
    2019年7月训练(柒)
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/9275c6a968a1b6c456e817c14c6d3ccf.html
Copyright © 2011-2022 走看看