单链表删除

123 阅读1分钟

题目:设计一个递归算法,删除一个不带头结点的单链表中所有值为x的节点
分析:
首先我们要创建单链表,并赋值,然后递归去判断值,进行删除

代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
struct Delete
{
	int value;
	struct Delete *next;
};
void deleteX(Delete *&p,int delNum) {//这里的第一个函数参数必须是引用值,不然会导致断链
	struct Delete *pre;//定义一个指针,进行删除
	if (p == NULL) return ;
	if (p->value == delNum) {
		pre = p;
		p = p->next;
		free(pre);
		deleteX(p,delNum);
	}
	else 
		deleteX(p->next, delNum);
}
int main() {
	struct Delete *p,*q,*head;
	int count = 0;
	q = (struct Delete *)malloc(sizeof(struct Delete));
	head = (struct Delete *)malloc(sizeof(struct Delete));
	int value,delNum;
	printf("请输入链表各节点的值,以-1结束:");
	scanf("%d", &value);
	while (value != -1 ) {//依次创建节点
		p = (struct Delete *)malloc(sizeof(struct Delete));
		p->value = value;
		p->next = NULL;
		if (count++==0) {
			q = p;
			head = p;
		}
		else {
			q->next = p;
			q = p;
		}
		scanf("%d",&value);
	}
	q->next = NULL;
	q = head;
	printf("打印链表:");
	while (q!=NULL) {
		printf("%d ",q->value);
		q = q->next;
	}
	q = head;
	printf("请输入想要删除的节点的值:");
	scanf("%d",&delNum);
	deleteX(q,delNum);
	printf("删除后链表:");
	while (q != NULL) {
		printf("%d ", q->value);
		q = q->next;
	}
	return 0;
}

注:删除函数的参数必须是引用值,因为引用直接代表原始值,在递归中就不会断链

众人笑我太疯癫,我笑他人看不穿!