数据结构 C++指定数值删除元素

前两篇中的删除是指定结点删除,这里指定数值删除,即需要先查找该数值元素的位置,然后利用前驱结点实现删除

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

}

主要参考:        《数据结构与算法》(第五版)张岩

                          《数据结构考研复习指导》(王道)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值