PTA 6-12 shared suffix list (25 points)

There is a method of storing the English word, letter of the word is all the strings in a single linked list. In order to save a little space, if there are two words that have the same suffix, let them share the suffix. The following figure shows the word "loading" and "being" forms of storage. This question asks you to identify two common suffix list.
Here Insert Picture Description
Function interface definition:

PtrToNode Suffix( List L1, List L2 );

Wherein List structure is defined as:

typedef struct Node *PtrToNode;
struct Node {
    ElementType Data; /* 存储结点数据 */
    PtrToNode   Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */

L1 and L2 are given lead single linked list node. Suffix function should return to the start position of the common suffix L1 and L2.

Referee test program Example:

#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;

typedef struct Node *PtrToNode;
struct Node {
    ElementType Data; /* 存储结点数据 */
    PtrToNode   Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */

void ReadInput( List L1, List L2 ); /* 裁判实现,细节不表 */
void PrintSublist( PtrToNode StartP ); /* 裁判实现,细节不表 */
PtrToNode Suffix( List L1, List L2 );

int main()
{
    List L1, L2
    PtrToNode P;

    L1 = (List)malloc(sizeof(struct Node));
    L2 = (List)malloc(sizeof(struct Node));
    L1->Next = L2->Next = NULL;
    ReadInput( L1, L2 );
    P = Suffix( L1, L2 );
    PrintSublist( P );

    return 0;
}

/* 你的代码将被嵌在这里 */

Input Sample:
Here Insert Picture Description
sample output:
ING

This question is there is an important point, that is, two lists of pointers point to the same address when a position is shared suffix, I started to think that one by one to find the suffix.
The method is: to traverse the list again, the length of the two lists respectively len1, LEN2, and then find that the longer the length of a two assumed len1 longer, then let tmp = len1-len2, refers to the pointer p1 tmp position and two rearward while moving the pointer of the list, until the address pointer is the same, is also desired.

AC Code:

PtrToNode Suffix( List L1, List L2 )
{
    int len1=-1,len2=-1;
    List p1=L1,p2=L2;
    while(p1!=NULL)
    {
        len1++;
        p1=p1->Next;
    }
    while(p2!=NULL)
    {
        len2++;
        p2=p2->Next;
    }
    int tmp;
    p1=L1,p2=L2;
    if(len1>len2)
    {
        tmp=len1-len2;
        while(tmp--)
        {
            p1=p1->Next;
        }
    }
    else
        if(len1<len2)
    {
        tmp=len2-len1;
        while(tmp--)
        {
            p2=p2->Next;
        }
    }
    while(p1!=NULL&&p1!=p2)
    {
        p1=p1->Next;
        p2=p2->Next;
    }
    if(p1!=NULL)
        return p1;
    return NULL;
}
Published 32 original articles · won praise 12 · views 1367

Guess you like

Origin blog.csdn.net/qq_18873031/article/details/103215502