查找两个单链表的公共结点

/*给定两个单链表,编写算法找出两个链表的公共结点*/
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode
{
	ElemType data;
	struct LNode *next;
}LNode,*LinkList;

LinkList TailCreateList(LinkList &L)
{
	L = (LinkList)malloc(sizeof(LNode));
	ElemType x;
	LNode *r = L;
	scanf("%d",&x);
	while(x!=9999)
	{
		LNode *s = (LNode*)malloc(sizeof(LNode));
		s->data = x;
		r->next = s;
		r = s;
		scanf("%d",&x);
	}
	r->next = NULL;
	return L;
}

int getListLen(LinkList L)
{
	int count = 0;
	LNode *p = L->next;
	while(p)
	{
		count++;
		p = p->next;
	}
	return count;
}

LNode *findCommonLNode(LinkList L1,LinkList L2)
{
	int len1 = getListLen(L1);
	int len2 = getListLen(L2);
	int dist;
	LNode *longpoint;
	LNode *shortpoint;
	if(len1<=len2)
	{
		longpoint = L2->next;
		shortpoint = L1->next;
		dist = len2 - len1;
	}else{
		longpoint = L1->next;
		shortpoint = L2->next;
		dist = len1 - len2;
	}
	while(dist--)
		longpoint = longpoint->next;
	while(longpoint!=NULL)
	{
		//只有是一个公共结点则后面全是公共结点,呈现Y型
		if(longpoint == shortpoint)
			return longpoint;
		else{
			longpoint = longpoint->next;
			shortpoint = shortpoint->next;
		}
	}
	return NULL;
}

bool printList(LinkList L)
{
	LNode *p = L->next;
	while(p!=NULL)
	{
		printf("%d ",p->data);
		p = p->next;
	}
	printf("\n");
	return true;
}

void main()
{
	LinkList L1,L2;
	TailCreateList(L1);
	printf("L1表长为:%d\n",getListLen(L1));
	printList(L1);
	TailCreateList(L2);
	printf("L2表长为:%d\n",getListLen(L2));
	printList(L2);
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值