递归算法-删除不带头结点的单链表中所有值为x的结点(后继结点删法)

#include <iostream>
using namespace std;
typedef struct LNode
{
    int data;
    struct LNode *next;
} LNode, *LinkList;
//112212 Null
void DeleteElem(LinkList &L, int e)
{

    LNode *p;
    if (L == NULL)
        return;
    if (L->data == e)
    {
        if (L->next == NULL)
        {

            cout << "Delete" << L->data << endl;
            delete L;
            L = NULL;

            return;
        }
        p = L->next;

        cout << "Delete" << L->data << endl;
        //代父受过
        L->data = p->data;
        L->next = p->next;
        delete p;
        DeleteElem(L, e);
    }
    else
    {
        DeleteElem(L->next, e);
    }
}
void PrintList(LinkList L)
{
    while (L->next != NULL)
    {
        cout << L->data << "-->";
        L = L->next;
    }
    cout << L->data;
    cout << endl;
}
int main()
{
    LinkList L = new LNode;
    L->next = NULL;
    LNode *p = new LNode;
    LNode *q = new LNode;
    LNode *r = new LNode;
    LNode *s = new LNode;
    LNode *t = new LNode;
    LNode *u = new LNode;
    L = p;
    p->next = q;
    q->next = r;
    r->next = s;
    s->next = t;
    t->next = u;
    u->next = NULL;
    p->data = q->data = t->data = 1;
    r->data = s->data = u->data = 2;
    PrintList(L);
    DeleteElem(L, 2);
    PrintList(L);
    cout << "success";
}
上一篇:2.3.2单链表基本操作(不带头节点)


下一篇:2021-08-05 王道 数据结构 p38 第2题