建两条双向链表,然后从后向前比较
#include<stdio.h>
#define SIZE 100000
struct list{
int add;
struct list *next, *forward;
char key;
};
struct Node{
int add,next;
char key;
}node[SIZE];
int main(){
freopen("1.in", "r", stdin);
int n, starta, startb;
scanf("%d%d%d", &starta, &startb, &n);
int i;
for (i = 0; i < n; i++)
scanf("%d %c %d", &node[i].add, &node[i].key, &node[i].next);
int next;
struct list *ha,*ta;
ha = new struct list;
ha->next = NULL;
ta = ha;
next = starta;
while (next != -1){
for (i = 0; i < n;i++)
if (node[i].add == next){
struct list *nd = new struct list;
nd->add = next;
nd->key = node[i].key;
nd->next = NULL;
nd->forward = ta;
if (ta == ha)
ha->next = nd;
ta->next = nd;
ta = nd;
next = node[i].next;
}
}
struct list *hb, *tb;
hb = new struct list;
hb->next = NULL;
tb = hb;
next = startb;
while (next != -1){
for (i = 0; i < n; i++)
if (node[i].add == next){
struct list *nd = new struct list;
nd->add = next;
nd->key = node[i].key;
nd->next = NULL;
nd->forward = tb;
if (tb == hb)
hb->next = nd;
tb->next = nd;
tb = nd;
next = node[i].next;
}
}
struct list *pa, *pb;
pa = ta;
pb = tb;
while (pa != ha&&pb != hb){
if (pa->add != pb->add)
break;
pa = pa->forward;
pb = pb->forward;
}
if (pa->next)
printf("%05d\n", pa->next->add);
else printf("-1\n");
return 0;
}
本文介绍了一种通过建立两个双向链表并从尾部开始比较的方法来寻找两个链表的交点。首先读取输入数据,构造两个链表,然后从链表尾部开始逐个节点向前比较,直到找到不同的节点或到达链表头部。
2005

被折叠的 条评论
为什么被折叠?



