题目描述:
给定两个单链表,编写算法找出两个链表的公共结点。
算法思想:
核心代码:
#include <stdio.h>
#include <algorithm>
typedef struct LNode//如果不在这里加LNode,结构体内的LNode*就会报错
{
int data;
LNode* next;
}LNode;
int Length(LNode* L)//注意:这里之前写成了int Length(LNode* &L)用的引用。
//这样的话,head1和head2最后都会变成NULL。难怪执行不对。
{
int k=0;
while(L!=NULL)
{
k++;
L=L->next;
}
return k;
}
LNode* Find_Pubilc_Node(LNode* &head1,LNode* &head2)//不带头结点
{
int len1=Length(head1);
int len2=Length(head2);
int longlen,shortlen;
LNode *longlist,*shortlist;
if(len1>len2)
{
longlen=len1;//或者不用记录longlen,shortlen。在这里直接算出差值k。
shortlen=len2;
longlist=head1;
shortlist=head2;
}
else
{
longlen=len2;
shortlen=len1;