[Estructura de datos de King's Road de 2023] [Tabla lineal—página 40—01] Implementación completa de C y C++ (se puede ejecutar directamente)

~~~ ¿Cómo puede terminar el estilo de escritura de una manera aburrida, y la historia no reconoce lo ordinario al principio? ✌✌✌

Si necesita el código completo, puede seguir la cuenta pública a continuación y responder "código" en segundo plano para obtenerlo. Aguang espera su visita ~

Pregunta:
inserte la descripción de la imagen aquí
Diseñe un algoritmo recursivo para eliminar todos los nodos con valor x en una lista enlazada L sin un nodo principal.

Ideas para resolver problemas:

>利用递归,不断将节点的下个节点传入函数
>每个函数执行对应删除操作

Código:

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

Supongo que te gusta

Origin blog.csdn.net/m0_47256162/article/details/124460407
Recomendado
Clasificación