File tree 4 files changed +134
-0
lines changed
160.Intersection of Two Linked Lists
4 files changed +134
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 相交链表
2
+ ### 题目描述
3
+
4
+ 编写一个程序,找到两个单链表相交的起始节点。
5
+
6
+
7
+ 示例 1:
8
+
9
+ 例如,下面的两个链表:
10
+
11
+ A: a1 → a2
12
+ ↘
13
+ c1 → c2 → c3
14
+ ↗
15
+ B: b1 → b2 → b3
16
+ 在节点 c1 开始相交。
17
+
18
+
19
+ 注意:
20
+
21
+ 如果两个链表没有交点,返回 null.
22
+ 在返回结果后,两个链表仍须保持原有的结构。
23
+ 可假定整个链表结构中没有循环。
24
+ 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
25
+
26
+ ### 解法
27
+ 第一遍循环,找出两个链表的长度差N
28
+ 第二遍循环,长链表先走N步,然后同时移动,判断是否有相同节点
29
+
30
+ ``` java
31
+ /**
32
+ * Definition for singly-linked list.
33
+ * public class ListNode {
34
+ * int val;
35
+ * ListNode next;
36
+ * ListNode(int x) {
37
+ * val = x;
38
+ * next = null;
39
+ * }
40
+ * }
41
+ */
42
+ public class Solution {
43
+ public ListNode getIntersectionNode (ListNode headA , ListNode headB ) {
44
+ if (headA == null || headB == null )
45
+ return null ;
46
+ ListNode p = headA;
47
+ ListNode q = headB;
48
+ int pCount = 0 ;
49
+ int qCount = 0 ;
50
+ while (p. next != null || q. next != null ){
51
+ if (p == q)
52
+ return p;
53
+
54
+ if (p. next != null )
55
+ p = p. next;
56
+ else
57
+ qCount++ ;
58
+
59
+ if (q. next != null )
60
+ q = q. next;
61
+ else
62
+ pCount++ ;
63
+ }
64
+ if (p != q)
65
+ return null ;
66
+ p = headA;
67
+ q = headB;
68
+ while (pCount-- != 0 ){
69
+ p = p. next;
70
+ }
71
+ while (qCount-- != 0 ){
72
+ q = q. next;
73
+ }
74
+ while (p != q){
75
+ p = p. next;
76
+ q = q. next;
77
+ }
78
+
79
+ return p;
80
+
81
+
82
+ }
83
+ }
84
+ ```
Original file line number Diff line number Diff line change
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
+ if (headA == null || headB == null )
15
+ return null ;
16
+ ListNode p = headA ;
17
+ ListNode q = headB ;
18
+ int pCount = 0 ;
19
+ int qCount = 0 ;
20
+ while (p .next != null || q .next != null ){
21
+ if (p == q )
22
+ return p ;
23
+
24
+ if (p .next != null )
25
+ p = p .next ;
26
+ else
27
+ qCount ++;
28
+
29
+ if (q .next != null )
30
+ q = q .next ;
31
+ else
32
+ pCount ++;
33
+ }
34
+ if (p != q )
35
+ return null ;
36
+ p = headA ;
37
+ q = headB ;
38
+ while (pCount -- != 0 ){
39
+ p = p .next ;
40
+ }
41
+ while (qCount -- != 0 ){
42
+ q = q .next ;
43
+ }
44
+ while (p != q ){
45
+ p = p .next ;
46
+ q = q .next ;
47
+ }
48
+ return p ;
49
+ }
50
+ }
You can’t perform that action at this time.
0 commit comments