面试题 02.07. 链表相交 - 力扣(Leetcode)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//链表相交 02.07.
public class IntersectionOfTwoLinkedListsLcci02_07 {
public static void main(String[] args){
ListNode headA = initLinkedList(new int[]{3,9,8,7});
ListNode headB = initLinkedList(new int[]{11,5,4,4});
ListNode temp = initLinkedList(new int[]{3,2,1,3});
ListNode cur = headA;
while(cur.next != null){
cur = cur.next;
}
cur.next = temp;
printLinkedList(new Solution().getIntersectionNode(headB,headA));
}

public static ListNode initLinkedList(int[] nums){
ListNode head = new ListNode(nums[0]);
ListNode cur = head,node;
for(int i = 1; i < nums.length; i++){
node = new ListNode(nums[i]);
cur.next = node;
cur = node;
}
return head;
}
public static void printLinkedList(ListNode head){
System.out.println();
ListNode cur = head;
while(cur != null){
System.out.print(cur.val + "->");
cur = cur.next;
}
System.out.println();
}
}

class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA;
ListNode curB = headB;

int lenA = 0,lenB = 0;
//两个链表的长度
while (curA != null){
curA = curA.next;
lenA++;
}
while (curB != null){
curB = curB.next;
lenB++;
}
curA = headA;
curB = headB;

//调整为 A 就是长的
if (lenA < lenB) {
int temp = lenA;
lenA = lenB;
lenB = temp;

ListNode tempNode = curA;
curA = curB;
curB = tempNode;
}
//把 curA 调到和 curB 一样的位置
int gap = lenA - lenB;
while(gap-- > 0){
curA = curA.next;
}

//真的调整
while (curA != null){
if (curA == curB) {
return curA;
}
curA = curA.next;
curB = curB.next;
}
return null;

}
}

class ListNode {
int val;
ListNode next;
public ListNode (){}
public ListNode (int val){
this.val = val;
}
public ListNode (int val, ListNode next){
this.val = val;
this.next = next;
}
}

反思:

3,11,5,4,3

11,5,4,9

会返回11

实际上:

image-20230327153340375