mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
@ -234,25 +234,19 @@ class Solution:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
```func detectCycle(head *ListNode) *ListNode {
|
```go
|
||||||
if head ==nil{
|
func detectCycle(head *ListNode) *ListNode {
|
||||||
|
slow, fast := head, head
|
||||||
|
for fast != nil && fast.Next != nil {
|
||||||
|
slow = slow.Next
|
||||||
|
fast = fast.Next.Next
|
||||||
|
if slow == fast {
|
||||||
|
for slow != head {
|
||||||
|
slow = slow.Next
|
||||||
|
head = head.Next
|
||||||
|
}
|
||||||
return head
|
return head
|
||||||
}
|
}
|
||||||
slow:=head
|
|
||||||
fast:=head.Next
|
|
||||||
|
|
||||||
for fast!=nil&&fast.Next!=nil{
|
|
||||||
if fast==slow{
|
|
||||||
slow=head
|
|
||||||
fast=fast.Next
|
|
||||||
for fast!=slow {
|
|
||||||
fast=fast.Next
|
|
||||||
slow=slow.Next
|
|
||||||
}
|
|
||||||
return slow
|
|
||||||
}
|
|
||||||
fast=fast.Next.Next
|
|
||||||
slow=slow.Next
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -155,6 +155,42 @@ Python:
|
|||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func getIntersectionNode(headA, headB *ListNode) *ListNode {
|
||||||
|
curA := headA
|
||||||
|
curB := headB
|
||||||
|
lenA, lenB := 0, 0
|
||||||
|
// 求A,B的长度
|
||||||
|
for curA != nil {
|
||||||
|
curA = curA.Next
|
||||||
|
lenA++
|
||||||
|
}
|
||||||
|
for curB != nil {
|
||||||
|
curB = curB.Next
|
||||||
|
lenB++
|
||||||
|
}
|
||||||
|
var step int
|
||||||
|
var fast, slow *ListNode
|
||||||
|
// 请求长度差,并且让更长的链表先走相差的长度
|
||||||
|
if lenA > lenB {
|
||||||
|
step = lenA - lenB
|
||||||
|
fast, slow = headA, headB
|
||||||
|
} else {
|
||||||
|
step = lenB - lenA
|
||||||
|
fast, slow = headB, headA
|
||||||
|
}
|
||||||
|
for i:=0; i < step; i++ {
|
||||||
|
fast = fast.Next
|
||||||
|
}
|
||||||
|
// 遍历两个链表遇到相同则跳出遍历
|
||||||
|
for fast != slow {
|
||||||
|
fast = fast.Next
|
||||||
|
slow = slow.Next
|
||||||
|
}
|
||||||
|
return fast
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
javaScript:
|
javaScript:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
Reference in New Issue
Block a user