我是靠谱客的博主 哭泣雨,这篇文章主要介绍PTA 有序链表的合并,现在分享给大家,希望可以做个参考。

题意:将两个非递减的链表合并,合并之后的链表仍为非递减的。
原题链接
代码:

#include <iostream>
using namespace std;

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

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;
}
List Union(List L1, List L2)
{
    Node *p = L1;
    Node *i = L1->next, *j = L2->next;
    while (i && j)
    {
        if (i->data <= j->data) 
        {
            p->next = i;
            i = i->next;
        }
        else 
        {
            p->next = j;
            j = j->next;
        }
        p = p->next;
    }
    if (i) p->next = i; //处理剩余部分
    if (j) p->next = j;
    return L1;
}

int main()
{
    List L1, L2;
    CreateList(L1);
    CreateList(L2);
    List L = Union(L1, L2);
    if (L->next == NULL) cout << "NULL";  //空链表的判断
    else PrintList(L);
    return 0;
}

变式:求并集序列的中位数
原题链接

#include <iostream>
using namespace std;

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

int n;

void CreateList(List &L)
{
    L = new Node;
    L->next = NULL;
    Node *tail = L;

    for (int i = 0; i < n; i ++)
    {
        Node *p = new Node;
        cin >> p->data;
        p->next = NULL;
        tail->next = p;
        tail = p;
    }
}
void PrintList(List L)
{
    Node *p = L->next;
    while (p)
    {
        cout << p->data;
        if (p->next) cout << ' ';
        p = p->next;
    }
}
List Union(List L1, List L2)
{
    Node *p = L1;
    Node *i = L1->next, *j = L2->next;
    while (i && j)
    {
        if (i->data <= j->data) 
        {
            p->next = i;
            i = i->next;
        }
        else 
        {
            p->next = j;
            j = j->next;
        }
        p = p->next;
    }
    if (i) p->next = i;
    if (j) p->next = j;
    return L1;
}
int main()
{
    cin >> n;

    List L1, L2;
    CreateList(L1);
    CreateList(L2);

    List L = Union(L1, L2);
    int cnt = 0;
    Node *p = L;
    while (cnt < (2 * n + 1) / 2)
    {
        p = p->next;
        cnt ++;
    }
    cout << p->data;
    return 0;
}

最后

以上就是哭泣雨最近收集整理的关于PTA 有序链表的合并的全部内容,更多相关PTA内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部