PAT A1032

很简单的一题,两个链表共用尾节点,找出第一个共用节点的地址。

主要思路:先求两个链表的表长,然后将长的一个先行遍历,直至两者相等,然后两表同时遍历,找到公共节点,将其输出。

坑点:因为用int存储的地址,注意输出格式补齐5位


AC代码如下

#include <iostream>
#include <cstring>
using namespace std;

const int max_n = 100010;

struct Node{
	char c;
	int next;
} node[max_n];

int charlen(int head){
	int len = 1;
	if(head == -1) return 0;
	while(node[head].next != -1){
		len++;
		head = node[head].next;
	} 
	return len;
}

int main(){
	int fh,sh,N;
	cin>>fh>>sh>>N;
	int add,nadd;
	char tem;
	for(int i = 0; i < N;i++){
		cin>>add>>tem>>nadd;
		node[add].c = tem;
		node[add].next = nadd;
	}
	int flen = charlen(fh) , slen = charlen(sh);
	//将较长字符串先遍历,直至两者相等 
	if(flen >= slen){
		for(int i = 0; i < flen - slen; i++){
			fh = node[fh].next;
		}
	}
	else{
		for(int i = 0; i < slen - flen; i++){
			sh = node[sh].next;
		}
	}
	//两者同时向后遍历直至找到相同节点 
	while(fh != sh){
		fh = node[fh].next;
		sh = node[sh].next;
	} 
	if(fh != -1) {
		printf("%05d",fh); 
	}
	else printf("-1");
	
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值