[2023 King's Road Data Structure] [Linear Table—page40—02] 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
In the singly linked list L with the head node, delete all nodes whose value is x and release their space. Assuming that the node whose value is x is not unique, try to write an algorithm to achieve the above operation.

Problem solving ideas:

>定义工作指针p、前驱指针pre
>遍历链表,删除元素

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 DelValue(LinkList &L, int x)
{
    LNode *p, *pre;
    p = L->next, pre = L;

    while (p)
    {
        if (p->data == x)
        {
            LNode *q = p;
            pre->next = p->next;
            p = p->next;
            delete q;
        }
        else
        {
            pre = p;
            p = p->next;
        }
    }
}

int main()
{
    LinkList L = new LNode;
    TailInsert(L);

    DelValue(L, 2);
    Print(L);
}

Guess you like

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