mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Update 面试题02.07.链表相交.md
增加了一种java语言的同步移动方法
This commit is contained in:
@ -105,6 +105,7 @@ public:
|
||||
### Java:
|
||||
|
||||
```Java
|
||||
(版本一)先行移动长链表实现同步移动
|
||||
public class Solution {
|
||||
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
|
||||
ListNode curA = headA;
|
||||
@ -149,6 +150,23 @@ public class Solution {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
(版本二) 合并链表实现同步移动
|
||||
public class Solution {
|
||||
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
|
||||
// p1 指向 A 链表头结点,p2 指向 B 链表头结点
|
||||
ListNode p1 = headA, p2 = headB;
|
||||
while (p1 != p2) {
|
||||
// p1 走一步,如果走到 A 链表末尾,转到 B 链表
|
||||
if (p1 == null) p1 = headB;
|
||||
else p1 = p1.next;
|
||||
// p2 走一步,如果走到 B 链表末尾,转到 A 链表
|
||||
if (p2 == null) p2 = headA;
|
||||
else p2 = p2.next;
|
||||
}
|
||||
return p1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Python:
|
||||
|
Reference in New Issue
Block a user