[2023 King's Road Data Structure] [Linear Table—page40—15] Complete implementation of C and C++ (can be run directly)

~~~How can the writing style end in a dull way, and the story does not recognize ordinary at the beginning ✌✌✌

If you need the complete code, you can follow the public account below, and reply "code" in the background to get it. Aguang is looking forward to your visit~

Question:
insert image description here
It is known that two linked lists A and B respectively represent two sets, and their elements are arranged in increasing order, formulate a function to find the intersection of A and B, and store them in the A linked list.

Problem solving ideas:

>类似归并排序
>将不等结点释放,相等结点进行尾插

Code:

#include <iostream>
using namespace std;

typedef struct LNode
{
    int data;
    struct LNode *next;
} LNode, *LinkList;

// 头插法
void HeadInsert(LinkList &L)
{
    int val = 0;
    while (cin >> val)
    {
        LNode *s = new LNode;
        s->data = val;
        s->next = L->next;
        L->next = s;

        if (cin.get() == '\n')
        {
            break;
        }
    }
}

// 尾插法
void TailInsert(LinkList &L)
{
    int val = 0;
    LNode *r = L;
    while (cin >> val)
    {
        LNode *s = new LNode;
        s->data = val;
        r->next = s;
        r = s;
        r->next = NULL;

        if (cin.get() == '\n')
        {
            break;
        }
    }
}

// 遍历输出链表元素
void Print(LinkList L)
{
    LNode *p = L->next;
    while (p)
    {
        cout << p->data << '\t';
        p = p->next;
    }
    cout << endl;
}

void PublicNode(LinkList &LA, LinkList &LB)
{
    LNode *pa, *pb, *r, *q; //定义两个链表的工作结点和尾插指针
    pa = LA->next;
    pb = LB->next;
    r = LA;

    while (pa && pb)
    {
        //如果pa小于pb,则将其删除,同时指针后移
        if (pa->data < pb->data)
        {
            q = pa;
            pa = pa->next;
            delete q;
        }
        else if (pa->data > pb->data)
        {
            q = pb;
            pb = pb->next;
            delete q;
        }
        //如果相等将pa尾插,删除pb
        else
        {
            r->next = pa;
            r = pa;
            pa = pa->next;
            q = pb;
            pb = pb->next;
            delete q;
        }
    }

    //将剩余所有结点全部释放
    while (pa)
    {
        q = pa;
        pa = pa->next;
        delete q;
    }

    while (pb)
    {
        q = pb;
        pb = pb->next;
        delete q;
    }

    r->next = NULL;
    delete LB;
}

int main()
{
    LinkList LA = new LNode;
    LinkList LB = new LNode;

    TailInsert(LA);
    TailInsert(LB);

    PublicNode(LA, LB);
    Print(LA);
}

Guess you like

Origin blog.csdn.net/m0_47256162/article/details/124470155