日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode OJ 160. Intersection of Two Linked Lists

發布時間:2023/12/10 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode OJ 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.

這個題目是要找出兩個鏈表的交叉點,該如何解決呢?如果兩個鏈表相交,我們從A鏈表出發移動一段距離alen,出B列表出發移動一段距離blen,那么會發現他們指向同一個節點c1。那么這個距離是多少呢?

我們把每一個鏈表看成兩段,不相交的一段和相交的一段。相交的一段對于兩個鏈表長度是一樣的,不想交的一段鏈表的長度是不同的。如果我們分別計算出兩個鏈表的長度,然后計算他們長度的差值f,然后在較長的鏈表上先移動距離f,再同時從A,B鏈表出發開始遍歷,若發現他們指向同一個節點,則他們相交并返回相交的點,若他們不想交,則會遍歷到鏈表的尾部,則返回null。代碼如下:

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 */ 12 public class Solution { 13 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 14 ListNode p1 = headA, p2 = headB; 15 int len1 = 0, len2 = 0; 16 while (p1 != null) { //求鏈表A的長度 17 p1 = p1.next; 18 len1++; 19 } 20 while (p2 != null) { //求鏈表B的長度 21 p2 = p2.next; 22 len2++; 23 } 24 p1 = headA; 25 p2 = headB; 26 if (len1 > len2) { //計算鏈表長度的差值并在較長的鏈表上向后移動|len1-len2| 27 for (int i = 0;i < len1 - len2; i++) { 28 p1 = p1.next; 29 } 30 } else { 31 for (int i = 0;i < len2 - len1; i++) { 32 p2 = p2.next; 33 } 34 } 35 while (p1 != p2) { //向后遍歷鏈表A和鏈表B,找到相交的節點,若遍歷到最后,返回null 36 p1 = p1.next; 37 p2 = p2.next; 38 } 39 return p1; 40 } 41 }

?

轉載于:https://www.cnblogs.com/liujinhong/p/5386115.html

總結

以上是生活随笔為你收集整理的LeetCode OJ 160. Intersection of Two Linked Lists的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。