一、题目
二、代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
///必定是尾部相交 这个给的比较模糊
ListNode* count_node = new ListNode(0);
ListNode* A_node = new ListNode(0);
ListNode* B_node = new ListNode(0);
ListNode* return_node = new ListNode(0);
return_node=nullptr;
A_node=headA;
B_node=headB;
int length_of_A=0;
int length_of_B=0;
count_node=headA;
while(count_node!=nullptr)
{
length_of_A+=1;
count_node=count_node->next;
}
std::cout<<" length_of_A "<< length_of_A <<std::endl;
count_node=headB;
while(count_node!=nullptr)
{
length_of_B+=1;
count_node=count_node->next;
}
std::cout<<" length_of_B "<< length_of_B <<std::endl;
int difference_of_length=abs(length_of_B-length_of_A); //计算长度差值
std::cout<<" difference_of_length "<< difference_of_length <<std::endl;
//将链表的节点统一
int count_decrease_difference=0;
if(length_of_A<length_of_B)
{
while(count_decrease_difference<difference_of_length)
{
count_decrease_difference=count_decrease_difference+1;
B_node=B_node->next;
}
}
if(length_of_A>length_of_B)
{
while(count_decrease_difference<difference_of_length)
{
count_decrease_difference=count_decrease_difference+1;
A_node=A_node->next;
}
}
while(A_node!=nullptr)
{
std::cout<<" 此时节点A的数值 "<< A_node->val <<std::endl;
std::cout<<" 此时节点B的数值 "<< B_node->val <<std::endl;
if(A_node->val==B_node->val)
{
return_node=A_node;
break;
}
A_node=A_node->next;
B_node=B_node->next;
}
return return_node;
}
};
三、运行结果
判题系统有一些问题,此题运行通过大部分即可。