输入两个链表,找出它们的第一个公共节点(值)
方法1:在第一个链表上顺序遍历每个节点,没遍历一个节点时,在第二个链表上顺序遍历每个节点。
方法2:计算每个链表的长度,长的链表先遍历两个链表长度差个节点,然后两个链表同时遍历,当他们相等时停止
/*************************************************************************
> File Name: FindFirstCommon.c
> Author: cyf
> Mail: 1097189275@qq.com
> Created Time: 2016年03月23日 星期三 08时52分01秒
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define OK 1
typedef struct ListNode
{
int data;
struct ListNode *next;
}ListNode;
/*
* 创建一个链表
* 输入:链表指针的指针
* 输出:空
**/
void InitListHead(ListNode **pNode)
{
int item;
ListNode *temp,*target;
printf("输入节点的值,输入0完成初始化\n");
while(1)
{
scanf("%d",&item);
fflush(stdin);
if(item==0)
return;
if(*pNode==NULL)
{
*pNode=(ListNode *)malloc(sizeof(ListNode));
if(!pNode)
exit(0);
(*pNode)->data=item;
(*pNode)->next=NULL;
}
else
{
for(target=(*pNode);target->next!=NULL;target=target->next)
;
temp=(ListNode *)malloc(sizeof(ListNode));
if(!temp)
exit(0);
temp->data=item;
temp->next=target->next;
target->next=temp;
}
}
}
/*
* 获取链表的长度
* 输入:链表的指针
* 输出:链表的长度
* */
int GetListLength(ListNode *L)
{
int ListLength=0;
ListNode *pNode=L;
while(pNode!=NULL)
{
++ListLength;
pNode=pNode->next;
}
return ListLength;
}
/*
* 打印链表
* 输入:链表的指针
* 输出:空
* */
void PrintList(ListNode *L)
{
int data;
ListNode *pNode=L;
while(pNode!=NULL)
{
data=pNode->data;
pNode=pNode->next;
printf("%d ",data);
}
printf("\n");
}
/*
* 输入两个链表,找出它们的第一个公共节点(值)
* 输入:两个链表的指针
* 输出:公共节点的指针
* */
ListNode *FindFirstCommon(ListNode *pHead1, ListNode *pHead2)
{
int length1=GetListLength(pHead1);
int length2=GetListLength(pHead2);
int lengthDiff=length1-length2;
ListNode *pLong=pHead1;
ListNode *pShort=pHead2;
int i;
if(length2>length1){
lengthDiff=length2-length1;
pLong=pHead2;
pShort=pHead1;
}
for(i=0;i<lengthDiff;i++)
pLong=pLong->next;
while((pLong!=NULL)&&(pShort!=NULL)&&(pLong->data!=pShort->data))
{
pLong=pLong->next;
pShort=pShort->next;
}
ListNode *pCommon=pLong;
return pLong;
}
int main()
{
ListNode *L1=NULL,*L2=NULL;
printf("创建第一个链表:\n");
InitListHead(&L1);
PrintList(L1);
printf("创建第二个链表:\n");
InitListHead(&L2);
PrintList(L2);
ListNode *common=FindFirstCommon(L1,L2);
printf("公共节点的值:%d",common->data);
return 0;
}