输入两个链表,找出它们的第一个公共节点(值)

输入两个链表,找出它们的第一个公共节点(值)

方法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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yiluohan0307

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值