前两篇中的删除是指定结点删除,这里指定数值删除,即需要先查找该数值元素的位置,然后利用前驱结点实现删除
#include <iostream>
#include <malloc.h>
using namespace std;
typedef int Elementtype;
struct celltype {
Elementtype element;
celltype *next;
};
typedef celltype *LIST;
//需要前驱指针
LIST Delete(LIST &L1, Elementtype x) {
celltype *p = L1->next, *q, *pre = L1;//增加前驱结点
while (p != NULL) {
if (p->element == x) {
q = p;
p = p->next;
pre->next = p;//重点
delete q;
return L1;
} else {
pre = p;//重点
p = p->next;
}
}
cout << "\n" << "There has no " << x << "." << endl;
return L1;
}
int main() {
LIST L1;
L1 = (LIST)malloc(sizeof(celltype));
celltype *s1, *r1 = L1, *print1 = L1, *print2;
Elementtype a[5] = {1, 3, 5, 7, 9};
for (int i = 0; i < 5; i++) {
s1 = (celltype *)malloc(sizeof(celltype));
s1->element = a[i];
r1->next = s1;
r1 = s1;
}
r1->next = NULL;
cout << "LIST1:" << endl;
while (print1->next != NULL) {
cout << print1->next->element << " ";
print1 = print1->next;
}
LIST L2;
L2 = Delete(L1, 4);
print2 = L1;
cout << "\n" << "After delete LIST1:" << endl;
while (print2->next != NULL) {
cout << print2->next->element << " ";
print2 = print2->next;
}
return 0;
}
主要参考: 《数据结构与算法》(第五版)张岩
《数据结构考研复习指导》(王道)