[2023 King's Road Data Structure] [Linear Table—page40—01] 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
Design a recursive algorithm to delete all nodes with value x in a singly linked list L without a head node.

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 DelValue(LinkList &L, int x)
{
    if (L == NULL)
    {
        return;
    }

    LNode *p;
    if (L->data == x)
    {
        p = L;
        L = L->next;
        delete p;
        DelValue(L, x);
    }
    else
    {
        DelValue(L->next, x);
    }
}

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

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

Guess you like

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