PTA 两个有序链表序列的交集

题意:
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
原题链接
代码1:(时间复杂度较大,无法通过最后一个测试点)

struct Node 
{
    
    
    int data;
    Node *next;
};
typedef Node *List;

bool IFexist(List L, int x)
{
    
    
    Node *p = L->next;
    while (p)
    {
    
    
        if (p->data == x) return true;
        p = p->next;
    }
    return false;
}
void CreateList(List &L)
{
    
    
    L = new Node;
    L->next = NULL;
    Node *tail = L;

    int x;
    cin >> x;
    while (x != -1)
    {
    
    
        Node *p = new Node;
        p->data = x;
        p->next = NULL;
        tail->next = p;
        tail = p;

        cin >> x;
    }
}
void PrintList(List L)
{
    
    
    Node *p = L->next;
    while (p)
    {
    
    
        cout << p->data << ' ';
        p = p->next;
    }
    cout << endl;
}
void insert(List L, int x)
{
    
    
    Node *tmp = new Node;
    tmp->data = x;
    tmp->next = NULL;

    Node *p = L;
    while (p->next) p = p->next;
    p->next = tmp;
}
List f(List L1, List L2)
{
    
    
    Node *L3 = new Node;
    L3->next = NULL;

    Node *p = L1->next;
    while (p)
    {
    
    
        if (IFexist(L2, p->data)) insert(L3, p->data);
        p = p->next;
    }
    return L3;
}
int main()
{
    
    
    List L1, L2;
    CreateList(L1);
    CreateList(L2);
    List L = f(L1, L2);
    if (L->next == NULL) cout << "NULL";
    else PrintList(L);
    return 0;
}

代码2:(双指针算法优化)

List f(List L1, List L2)
{
    
    
    Node *L3 = new Node;
    L3->next = NULL;

    Node *i = L1->next, *j = L2->next;
    while (i && j) //i、j分别遍历两个链表,每个链表分别只遍历一次。
    {
    
    
        if (i->data < j->data) i = i->next;
        else if (j->data < i->data) j = j->next;
        else 
        {
    
    
            insert(L3, i->data);
            i = i->next;
            j = j->next;
        }
    }
    return L3;
}

int main()
{
    
    
    List L1, L2;
    CreateList(L1);
    CreateList(L2);
    List L = f(L1, L2);
    if (L->next == NULL) cout << "NULL";
    else PrintList(L);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Shao_yihao/article/details/121546839