递归删除单链表中值为x的结点(两种方法)

这个是引用方式,链表分带头结点与不带头结点,但是都可以用

#include<iostream>
using namespace std;


typedef struct LNode{
	int data;
	struct LNode *next;
}LNode,*LinkList;

//带头结点
LNode* create(int Array[]){
	LNode *p, *pre, *head;
	head = new LNode;
	head->data = NULL;
	pre = head;
	for (int i = 0; i < 8; i++){
		p = new LNode;
		p->data = Array[i];
		p->next = NULL;
		pre->next = p;
		pre = p;
	}
	return head;
}

//不带头结点
LNode* noheadcreate(int Array[]){
	LNode *p, *pre, *head = NULL;
	/*node *head = NULL;*/
	pre = head;
	for (int i = 0; i < 8; i++){
		//此处对头结点进行单独处理,不存在pre->next;
		if (head == pre){
			p = new LNode;
			p->next = NULL;
			p->data = Array[i];
			pre = p;
			head = p;
		}
		p = new LNode;
		p->data = Array[i];
		p->next = NULL;
		pre->next = p;
		pre = p;
	}
	return head;
}

///递归删除不带头结点的单链表中值为x的结点(带不带头结点都一样)

//经过测试,带不带头结点都是可以实现效果,
//有点晕,这是因为引用吗?不带头结点的时候竟然没有问题

void Del_x_1(LinkList &L, int x){//引用方式不会断链
	LNode *p;
	if (L == NULL) return;
	if (L->data == x){
		p = L;
		L = L->next;
		free(p);
		Del_x_1(L, x);
	}
	else
	{
		Del_x_1(L->next, x);
	}
}

int main(){
	//用不带头结点的方式创建单链表L01
	int Array01[8] = { 1, 3, 6, 6, 9,5,4,3 };
	LNode* L01 = noheadcreate(Array01);
	Del_x_1(L01,6);

	//用带头结点的方式创建单链表L02
	int Array02[8] = { 1, 3, 6, 6, 9, 5, 4, 3 };
	LNode* L02 = create(Array02);
	Del_x_1(L02, 3);


	//不用打印函数了,直接写吧,正好看看带不带头结点的打印方式不同之处
	cout << "递归删除不带头结点的单链表中值为6的结点:";
	while (L01->next != NULL){
		cout << L01->next->data;
		L01 = L01->next;
	};

	cout << endl;
	cout << "递归删除带头结点的单链表中值为3的结点:";
	while (L02->next != NULL){
		cout << L02->next->data;
		L02 = L02->next;
	};
	cout << endl;
	return 0;
}
在介绍一个普通的方法,使用指针写

#include<iostream>
using namespace std;

typedef struct LNode{
	int data;
	struct LNode *next;
}LNode, *Linklist;


//带头结点单链表的创建
LNode* create(int Array[]){
	LNode *p, *pre, *head;
	head = new LNode;
	head->data = NULL;
	pre = head;
	for (int i = 0; i < 5; i++){
		p = new LNode;
		p->data = Array[i];//链表的data域直接用数组的值传, 不直接输入了
		p->next = NULL;
		pre->next = p;
		pre = p;
	}
	return head;
}

void delete_x_1(LNode *head, int x){//head为单链表头结点,删除结点的值为x
	LNode *l = head;
	LNode *p = head->next;
	while (p != NULL){
		if (p->data == x){
			l->next = p->next;
			free(p);
			p = l->next; //要加上这句啊,因为直接销毁p后面又将p的地址给l,因为已经销毁了直接就为空了
		}				//在网上看了别人的代码是没有这句了,运行时出问题的
		l = p;
		p = p->next;
	} 
}

int main(){

	int Array01[5] = { 1, 3, 5, 7, 9 };
	LNode* L01 = create(Array01);
	
	delete_x_1(L01, 5);

	while (L01->next != NULL){
		cout << L01->next->data;
		L01 = L01->next;
	}

	return 0;
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值