当前位置:网站首页>Leetcode interview question 02.07 Linked list intersection [double pointer]
Leetcode interview question 02.07 Linked list intersection [double pointer]
2022-07-07 22:49:00 【Qingshan's green shirt】
LeetCode Interview questions 02.07. The list intersects
List of articles
1. subject
2. Ideas
It should be noted that :
1. If two linked lists intersect , From the intersection point to the end of the table are the same nodes , That is, the two become one .
2. The intersection here is determined by reference ! That is, the address of the node , Not the value of the node !
Ideas :
1. Count the length of two linked lists , Subtraction .
another : I thought about it a little more here , Go to the last node and judge whether they are the same , That is, judge whether the two linked lists intersect .
2. According to the form of tail alignment , The pointer of the long linked list goes first , Go until it is aligned with the header of the short linked list .
3. The two pointers go synchronously , Stop if intersecting .
3. Code implementation
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
//1. Special judgment head node , There is really no way to intersect an empty table
if(headA == NULL || headB == NULL) return NULL;// If it is empty, there is no ? exactly
//2. Create a dummy node - It is convenient for the pointer to stop at the last node when counting the length
ListNode* dummyA = new ListNode(-1);
dummyA->next = headA;
ListNode* dummyB = new ListNode(-1);
dummyB->next = headB;
ListNode*a = dummyA;
ListNode*b = dummyB;
int sizeA = 0;int sizeB = 0;
//3. Statistical length At this time, the pointer points to the last node , Not empty !
while(a->next != NULL)
{
a = a->next;
sizeA++;
}
while(b->next != NULL)
{
b = b->next;
sizeB++;
}
delete dummyA;delete dummyB;// Deleting is a good habit
//4. If the position of the last node is the same , Is intersecting . Discussion by situation
if(a == b)
{
if(sizeA > sizeB)//A Than B Long
{
//5. Length difference
int cnt = sizeA - sizeB;
ListNode* fast = headA;
ListNode* slow = headB;
//6. Let's go first , Align with the head of the slow pointer
while(cnt--)
fast = fast->next;
//7. Go at the same time , When you encounter the starting point of intersection, you return
while(fast != slow)
{
fast = fast->next;
slow = slow->next;
}
ListNode *m = fast;
return m;
}
else //if(sizeA <= sizeB) B Than A Long or equal
// It can only be else, The compiler thinks there are other cases ...
{
int cnt = sizeB - sizeA;
ListNode* fast = headB;
ListNode* slow = headA;
while(cnt--)
fast = fast->next; // Align with the head of the slow pointer
while(fast != slow)
{
fast = fast->next;
slow = slow->next;
}
ListNode *m = fast;
return m;
}
}
else return NULL;// Disjoint , Go straight back to
}
};
Post a more concise code of the boss , Redundant code generated by case discussion is omitted , Because it can be exchanged directly ! Just a little bit .
curA = headA;
curB = headB;
// Give Way curA For the head of the longest linked list ,lenA Is its length
if (lenB > lenA) {
swap (lenA, lenB);//lenA Save large value
swap (curA, curB);//curA Refers to the head of the long linked list
}
// Length difference
int gap = lenA - lenB;
// Length difference
int gap = lenA - lenB;
// Give Way curA and curB At the same starting point ( End position alignment )
while (gap--) {
curA = curA->next;
}
// Traverse curA and curB, If you encounter the same, you will directly return
while (curA != NULL) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
matters needing attention
There is a small one. tip: Count the length of the linked list. If you want the pointer to stop at the last node, you can use dummy nodes !
swap function : Exchange values at respective addresses . such as swap(a,b);a,b Are variables of the same data type .a,b The values of are assigned to b,a.
边栏推荐
- Unity technical notes (II) basic functions of scriptableobject
- Matplotlib快速入门
- The free styling service of Dyson's official direct store is now open for appointment. Pioneer Technology interprets the styling concept of hair care and helps consumers unlock diversified and shiny s
- How to choose the appropriate automated testing tools?
- Debezium系列之: 支持在 KILL 命令中使用变量
- 行测-图形推理-6-相似图形类
- Vs custom template - take the custom class template as an example
- OpenGL job coordinate system
- Revit secondary development - collision detection
- Debezium系列之:引入对 LATERAL 运算符的支持
猜你喜欢
Microservice Remote debug, nocalhost + rainbond microservice Development second Bomb
「开源摘星计划」Loki实现Harbor日志的高效管理
UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xf9 in position 56: illegal multibyte sequence
Robot autonomous exploration series papers environment code
Visual design form QT designer design gui single form program
Ni9185 and ni9234 hardware settings in Ni Max
Unity FAQ (I) lack of references
Leetcode1984. Minimum difference in student scores
0-5VAC转4-20mA交流电流隔离变送器/转换模块
Remember an experience of using selectmany
随机推荐
Digital transformation: five steps to promote enterprise progress
100million single men and women "online dating", supporting 13billion IPOs
戴森官方直营店免费造型服务现已开放预约 先锋科技诠释护发造型理念,助力消费者解锁多元闪耀造型
Leetcode1984. Minimum difference in student scores
C development - interprocess communication - named pipeline
微服务架构开源框架详情介绍
Microservice Remote debug, nocalhost + rainbond microservice Development second Bomb
Revit secondary development - intercept project error / warning pop-up
Time convolution Network + soft threshold + attention mechanism to realize residual life prediction of mechanical equipment
Gazebo import the mapping model created by blender
行测-图形推理-5-一笔画类
The free styling service of Dyson's official direct store is now open for appointment. Pioneer Technology interprets the styling concept of hair care and helps consumers unlock diversified and shiny s
Signal feature extraction +lstm to realize gear reducer fault diagnosis -matlab code
Form组件常用校验规则-2(持续更新中~)
IP网络主动测评系统——X-Vision
Unity local coordinates and world coordinates
Interview question 01.02 Determine whether it is character rearrangement - auxiliary array algorithm
Failed to initialize rosdep after installing ROS
Revit secondary development - collision detection
C # Development -- pit encountered in JS intermodulation