Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit abc86e9

Browse files
authored
Update 面试题02.07.链表相交.md
增加了一种java语言的同步移动方法
1 parent 7f33567 commit abc86e9

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

‎problems/面试题02.07.链表相交.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ public:
105105
### Java:
106106
107107
```Java
108+
(版本一)先行移动长链表实现同步移动
108109
public class Solution {
109110
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
110111
ListNode curA = headA;
@@ -149,6 +150,23 @@ public class Solution {
149150
}
150151
151152
}
153+
154+
(版本二) 合并链表实现同步移动
155+
public class Solution {
156+
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
157+
// p1 指向 A 链表头结点,p2 指向 B 链表头结点
158+
ListNode p1 = headA, p2 = headB;
159+
while (p1 != p2) {
160+
// p1 走一步,如果走到 A 链表末尾,转到 B 链表
161+
if (p1 == null) p1 = headB;
162+
else p1 = p1.next;
163+
// p2 走一步,如果走到 B 链表末尾,转到 A 链表
164+
if (p2 == null) p2 = headA;
165+
else p2 = p2.next;
166+
}
167+
return p1;
168+
}
169+
}
152170
```
153171

154172
### Python:

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /