160.相交链表
题目:编写一个程序,找到两个单链表相交的起始节点。
两个链表:
在节点 c1 开始相交。
输入:intersectVal = 8, listA
= [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node
with value = 8
输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为
[5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
方法一: 暴力法
对链表A中的每一个结点 ai,遍历链表B 检查其中是否存在结点ai。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
ListNode * cur_a = headA;
while(cur_a != NULL)
{
ListNode * cur_b = headB;
while(cur_b != NULL)
{
if(cur_a == cur_b) return cur_a;
cur_b = cur_b->next;
}
cur_a = cur_a->next;
}
return NULL;
}
};
方法二:
1.list_length成员函数求长度
2.move_pointer成员函数 移动指向头结点的指针
3. getIntersectionNode中首先计算headA,headB的长度lengthA, length
4.if判断A、B的长度,用move_pointer移动两者差值的长度
5.在AB不为空的条件下,若A和B所指向的节点相同,result = headA
6.若不同继续移动,最终跳出循环后返回result
class Solution {
int list_length(ListNode * head)
{
int length = 0;
while(head)
{
length++;
head = head->next;
}
return length;
}
ListNode * move_pointer(ListNode * head,int count)
{
for(int i = 0;i<count;i++)
{
head = head->next;
}
return head;
}
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
int lengthA = list_length(headA);
int lengthB = list_length(headB);
if (lengthA > lengthB)
{
headA = move_pointer(headA,lengthA - lengthB);
}
else
{
headB = move_pointer(headB,lengthB - lengthA);
}
ListNode * result = NULL;
while(headA && headB)
{
if (headA == headB)
{
result = headA;
break;
}
headA = headA->next;
headB = headB->next;
}
return result;
}
};