1. 程式人生 > 其它 >PAT刷題——1032 Sharing

PAT刷題——1032 Sharing

技術標籤:資料結構連結串列

題目連結:https://pintia.cn/problem-sets/994805342720868352/problems/994805460652113920

1032 Sharing (25 分)

To store English words, one method is to use linked lists and store a word letter by letter. To save some space, we may let the words share the same sublist if they share the same suffix. For example,loading

andbeingare stored as showed in Figure 1.

fig.jpg

Figure 1

You are supposed to find the starting position of the common suffix (e.g. the position ofiin Figure 1).

Input Specification:

Each input file contains one test case. For each case, the first line contains two addresses of nodes and a positiveN(≤10​5​​), where the two addresses are the addresses of the first nodes of the two words, andNis the total number of nodes. The address of a node is a 5-digit positive integer, and NULL is represented by−1.

ThenNlines follow, each describes a node in the format:

Address Data Next

whereAddressis the position of the node,Datais the letter contained by this node which is an English letter chosen from { a-z, A-Z }, andNextis the position of the next node.

Output Specification:

For each case, simply output the 5-digit starting position of the common suffix. If the two words have no common suffix, output-1

instead.

Sample Input 1:

11111 22222 9
67890 i 00002
00010 a 12345
00003 g -1
12345 D 67890
00002 n 00003
22222 B 23456
11111 L 00001
23456 e 67890
00001 o 00010

Sample Output 1:

67890

Sample Input 2:

00001 00002 4
00001 a 10001
10001 s -1
00002 a 10002
10002 t -1

Sample Output 2:

-1

題目大意:給定兩個連結串列,判斷這兩個連結串列是否有公共部分

解題思路:靜態連結串列方法,多定義一個flag變數,用來記錄flag是否在第一條連結串列中出現,是就是true,否false。從第一條連結串列首地址開始遍歷,經過的節點flag為true,列舉第二個節點,如果發現該節點flag值為true,說明是一個共用節點,如果沒有則輸出-1。不足5位的整數需要補0

程式碼:

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int ma = 100010;
struct node //靜態連結串列
{
    char data; //資料
    int next;  //下一個結點的地址
    bool flag; //標記
} a[ma];       //地址作為索引

int main()
{
    int n1, n2, n; //第一個連結串列和第二個連結串列的初始地址
    cin >> n1 >> n2 >> n;
    int index, next;
    char data;
    for (int i = 0; i < n; i++)
    {
        cin >> index;        //這個節點的地址
        cin >> data >> next; //資料及下一個節點的地址
        a[index] = {data, next, false};
    }
    for (int i = n1; i != -1; i = a[i].next)
    {
        a[i].flag = true; //第一個連結串列都標記為true
    }
    for (int i = n2; i != -1; i = a[i].next)
    {
        if (a[i].flag == true) //如果標記為true說明此節點是共同節點
        {
            printf("%05d", i);
            return 0;
        }
    }
    printf("-1");
    return 0;
}