160. 相交链表

图片说明

  • 双重遍历

    public class Solution {
      // 链表的节点完全相同应该就好理解了,并不是节点中的值相同。地址内存相同
      // 你不知道后面是否有跟前面一样的点
      // 双重遍历
      public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
          while (headA != null) {
              ListNode temp = headB;
              while (temp != null) {
                  if (headA == temp)
                      return headA;
                  temp = temp.next;
              }
              headA = headA.next;
          }
          return null;
      }
    }
  • 哈希表

    public class Solution {
      public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
          HashSet<ListNode> hs = new HashSet<ListNode>();
          while(headA!=null) {
              hs.add(headA);
              headA = headA.next;
          }
          while(headB!=null) {
              if(hs.contains(headB))
                  return headB;
              headB = headB.next;
          }
    
          return null;
      }
    }
  • 双指针

    public class Solution {
      // 链表的节点完全相同应该就好理解了,并不是节点中的值相同。地址内存相同
      // 你不知道后面是否有跟前面一样的点
      // 双重遍历
      public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
          int lenA = 0;
          int lenB = 0;
          ListNode tempA = headA;
          ListNode tempB = headB;
          while(tempA!=null) {
              lenA++;
              tempA = tempA.next;
          }
          while(tempB !=null) {
              lenB++;
              tempB = tempB.next;
          }
          if(lenA>lenB) {
              for(int i = 0 ; i < lenA-lenB ; i++) {
                  headA = headA.next;
              }
          }
          else {
              for(int i = 0 ; i < lenB - lenA; i++) {
                  headB = headB.next;
              }
          }
          while(headB!=null&&headA!=null) {
              if(headB == headA) {
                  return headB;
              }
              else {
                  headB = headB.next;
                  headA = headA.next;
              }
          }
          return null;
      }
    }
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 14:08
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
06-18 13:28
已编辑
门头沟学院 Web前端
爱睡觉的冰箱哥:《给予你300的工资》,阴的没边了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务