pat 1032. Sharing (25)

建两条双向链表,然后从后向前比较

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值