有一个不带头结点的单链表,设计一个算法删除其中所有结点值为x的结点

    科技2022-07-11  99

    对应的递归模型为:

    f(L,x)=不做任何事        ,                                    当L为NULL时;

    f(L,x)=删除L结点;L指向原后继结点,               当L->data=x时;

    f(L,x)=f(L->next,x)                                                当L->data!=x时

    源代码如下:

    #include <iostream> using namespace std; //单链表的结构体 typedef struct Node { int data; struct Node *next; }Node; //删除所有结点为x的结点 void DelX(Node *&L,int x) { //Node *q = L; if (L !=NULL) { if (L->data==x) { Node *p = (Node*)malloc(sizeof(Node)); p = L; L = L->next; DelX(L,x); free(p); } else { DelX(L->next, x); } } } //单链表的创建 void LinkCreate(Node *&L) { int a = 0; cout << "请输入数据" << endl; cin >> a; Node *r; r = L; while (a != 9999) { Node *p; p = (Node*)malloc(sizeof(Node)); p->data = a; p->next = NULL; if (L == NULL) { L = p; r = L; } else { r->next = p; r = p; } cin >> a; } } //单链表的输出,检验是否已经把所有的值为x的结点删除了 void display(Node *L){ while (L!=NULL) { cout << L->data<<" "; L = L->next; } cout << endl; } int main() { Node *L = NULL; LinkCreate(L); cout << "删除前的单链表的结点值为:" << endl; display(L); int x = 0; cout << "请输入要删除的结点值:" << endl; cin >> x; DelX(L,x); cout << "删除后的单链表的结点值为:" << endl; display(L); system("pause"); return 0; }

    输出结果为:

    请输入数据 15 25 35 65 45 55 65 9999 删除前的单链表的结点值为: 15 25 35 65 45 55 65 请输入要删除的结点值: 65 删除后的单链表的结点值为: 15 25 35 45 55 请按任意键继续. . .

     

     

    Processed: 0.036, SQL: 8