2.6-15对于不带头结点的单链表 L,设计一个递归算法删除第一个值为 x 的结点

#include "LinkList.cpp"
#include <bits/stdc++.h>

void Delfirstx(LinkNode *&L,int x) { // 删除第一个值为 x 的结点
	if (L==NULL)
		return;
	if (L->data==x) {
		LinkNode *p=L;
		L=L->next;
		free(p);
	} else
		Delfirstx(L->next,x);
}

int main() {
	int a[]= {1,2,5,2,3,2};
	int n=sizeof(a) / sizeof(a[0]);
	LinkNode *L;
	L = CreateList(a,n);
	cout << "删除前:";
	DispList(L);
	cout << endl; // 换行
	int x = 2;
	Delfirstx(L,x);
	cout << "删除后:";
	DispList(L);
	Release(L);  // 释放所有节点
	return 0;
}
#include<bits/stdc++.h>

using namespace std;

typedef struct Node {
	int data;
	struct Node *next;
} LinkNode;

LinkNode *CreateList(int a[],int n) {
	if(n < 0)
		return NULL;
	LinkNode *head = (LinkNode *)malloc(sizeof(LinkNode));
	LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode));
	p = head;
	head->data = a[0];
	int i = 0;
	for(i = 1; i < n; i++) {
	
		LinkNode *node = (LinkNode *)malloc(sizeof(LinkNode));
		node->data = a[i];
		p->next = node;
		p = node;
	}
	p->next = NULL;  // 尾结点next域置为空
	return head;
}

void DispList(LinkNode *ln) {
	cout << " "; 
	if(ln != NULL){
		cout << ln->data;
		DispList(ln->next);
	}
}

void Release(LinkNode *ln) {
	if(ln->next == NULL)
		return ;
	else {
		Release(ln->next);
		free(ln);
	}
}
  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值