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;
}

猜你喜欢

转载自blog.csdn.net/Shao_yihao/article/details/121546452
今日推荐