链表 笔记
链表笔记
- 判断是否有环 做法:龟兔赛跑,快慢指针
- 判断两链表是否相交,若相交则找出交点。
1struct ListNode
2{
3 int val;
4 ListNode *next;
5 ListNode(int x) : val(x), next(NULL) {}
6};
7
8class Solution
9{
10public:
11 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
12 {
13 ListNode *pA{headA}, *pB{headB};
14 while (pA != pB)
15 {
16 pA = pA == nullptr ? headB : pA->next;
17 pB = pB == nullptr ? headA : pB->next;
18 }
19 return pA;
20 }
21};