王道数据结构2022-线性表的链式表示-综合题(p41)-08给定两个单链表.编写算法找出两个链表的公共结点

给定两个单链表.编写算法找出两个链表的公共结点

#include<stdio.h>
#include<stdlib.h>

typedef struct LNode { //定义单链表结点类型
	int data;//数据域
	struct LNode *next;//指针域
} LNode, *LinkList;

/*给定两个单链表.编写算法找出两个链表的公共结点*/

//带头结点尾插法建立单链表
LinkList List_TailInsert(LinkList &L) { //正向建立单链表
	int x;
	L=(LinkList)malloc(sizeof(LNode));
	L->data=999999;
	LNode *s, *r=L;//r为表为指针
	printf("请输入数值\n");
	scanf("%d",&x);
	while(x!=9999) { //输入 9999表示结束
		s=(LNode *)malloc(sizeof(LNode));
		s->data = x;
		r->next = s;
		r=s;//r指向新的表尾结点
		scanf("%d",&x);
	}
	r->next = NULL;//尾结点指针置空
	return L;
}

//打印链表
void print(LinkList L) {
	printf("\n");
	if(L->next==NULL)
		printf("该链表为空");
	LNode *p= L->next;
	while(p!=NULL) {
		printf("%d ",p->data);
		p=p->next;
	}
}
//求表长
int Length(LinkList L) {
	int count=0;
	LNode *p=L->next;
	while(p!=NULL) {
		count++;
		p=p->next;
	}
	return count;
}
/*算法思想:
两个单链表有公共结点,即两个链表从某一结点开始,他们的next都指向同一个结点*/
LinkList Serach_lst_Common(LinkList L1,LinkList L2) {
	//本算法实现在线性时间内找到两个单链表的第一个公共结点
	int len1=Length(L1) ,len2=Length(L2);//计算两个链表的表长
	int dist;//两个链表表长的差值
	LinkList longList,shortList;//分别指向表长较长和较短的链表
	if(len1>len2) {//L1表较长
		longList = L1->next;
		shortList = L2->next;
		dist = len1 - len2;
	} else {
		longList = L2->next;
		shortList = L1->next;
		dist = len2 - len1;
	}
	while(dist--)//表长的链表先遍历到第dist个结点,然后同步
		longList = longList->next;
	while(longList!=NULL) {
		if(longList->data==shortList->data)//找到第一个公共结点
			return longList;
		else { //继续同步寻找
			longList = longList->next;
			shortList = shortList->next;
		}
	}
	return NULL;
}

int main() {
	LinkList L1,L2;
	int x;
	List_TailInsert(L1);
	List_TailInsert(L2);
	print(L1);
	print(L2);
	LinkList commonList;
	commonList=(LinkList)malloc(sizeof(LNode));
	commonList->data=999999;
	commonList->next= Serach_lst_Common(L1,L2);
	print(commonList);
	return 0;
}

运行效果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值