PAT-链表-A1032 Sharing

题意:给出两条链表的首地址以及若干个节点的的地址、数据、下一个节点的地址,求两条链表的首个共用节点的地址。如果两条链表没有共用节点,则输出-1。

思路:使用静态链表,首先遍历一遍第一个链表并进行标记。然后遍历第二个链表,并检查标记元素,得出结果,进行输出。

代码如下:


```cpp
//所用解法不涉及节点的数据及其地址,
//故不需要在节点中来存储

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1000000;

struct Node
{
//指向下一个地址,标记是否在第一个链表中
int next,flag;
};

Node datas[maxn];

int main()
{
int first1, first2, num;

//读取第一个链表的首地址,第二个链表的首地址,节点数目
scanf("%d %d %d", &first1, &first2, &num);

//获取节点数据
for (int i = 0;i < num;i++)
{
int add_temp, next_temp;
char data_temp;
scanf("%d %c %d", &add_temp, &data_temp, &next_temp);

datas[add_temp].next = next_temp;
}

//遍历第一个链表并进行标记
while (first1 != -1)
{
datas[first1].flag = 1;
first1 = datas[first1].next;
}

//遍历第二个链表,并由标记元素来寻找第一个共同节点
while (first2 != -1 && datas[first2].flag != 1)
{
first2 = datas[first2].next;
}

//输出结果
if (first2 == -1)printf("-1\n");
else printf("%05d\n", first2);

return 0;
}
```

猜你喜欢

转载自www.cnblogs.com/fangzhiyou/p/12347269.html
今日推荐