力扣https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/代码随想录
这种题感觉要记住解题套路
//
// Created by lwj on 2023-03-29.
//
//
#include <iostream>
using namespace std;
// 定义链表节点
struct ListNode {
int val;
ListNode *next;
ListNode(int val) : val(val), next(NULL) {}
};
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0, lenB = 0;
while (curA != NULL) { // 求链表A的长度
lenA++;
curA = curA->next;
}
while (curB != NULL) { // 求链表B的长度
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
// 让curA为最长链表的头,lenA为其长度 让两个链表中长的那个作为链表A
if (lenB > lenA) {
swap (lenA, lenB);
swap (curA, curB);
}
// 求长度差
int gap = lenA - lenB;
// 让curA和curB在同一起点上(末尾位置对齐)
while (gap--) {
curA = curA->next;
}
// 遍历curA 和 curB,遇到相同则直接返回
while (curA != NULL) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
// 测试代码
int main() {
// 创建两个链表
ListNode* headA = new ListNode(0);
headA->next = new ListNode(9);
headA->next->next = new ListNode(1);
headA->next->next->next = new ListNode(2);
headA->next->next->next->next = new ListNode(4);
ListNode* headB = new ListNode(3);
headB->next = new ListNode(2);
headB->next->next = new ListNode(4);
headB->next = headA->next->next->next;
// 调用函数,输出结果
Solution solution;
ListNode* intersectionNode = solution.getIntersectionNode(headA, headB);
if (intersectionNode != NULL) {
cout << "Intersection node value: " << intersectionNode->val << endl;
}
else {
cout << "No intersection node found." << endl;
}
return 0;
}