不带头结点的单链表删除任意一个节点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yp18792574062/article/details/75676504
#include<stdio.h>
#include<malloc.h>
//删除单链表中的任意一个节点,可能是传节点删除,也可能是传节点的值删除
typedef struct _Node
{
	int val;
	struct _Node* next;
}Node,*LinkList;
//不带头结点的单链表
void Init(LinkList* list)
{
	(*list) = NULL;
}
void Creat(LinkList* list)
{
	int data;
	scanf("%d", &data);
	while (data != 0)
	{
		Node* node = (Node*)malloc(sizeof(Node));
		node->val = data;
		node->next = NULL;
		if (*list == NULL)
		{
			*list = node;
		}
		else
		{
			Node* r = *list;
			while (r->next != NULL)
			{
				r = r->next;
			}
			r->next = node;
		}
		scanf("%d", &data);
	}
}
void Print(LinkList list)
{
	Node* r = list;
	while (r != NULL)
	{
		printf("%d ", r->val);
		r = r->next;
	}
	printf("\n");
}
/*
bool DeleteNode(Node* r,LinkList* list)
{
	if (*list == NULL || r == NULL)
	{
		return false;
	}
	Node* s = *list;
	while (s != NULL && s->next != r)
	{
		s = s->next;
	}
	if (s == NULL)
	{
		return false;
	}
	Node* k = s->next;
	s->next = s->next->next;
	free(k);
	return true;
}
*/
//根据节点删除,还有一种方法就是,把它下一个节点的数据给它自己,然后删除它的下一个节点
bool DeleteNode(Node* r, LinkList* list)
{
	if (*list == NULL || r == NULL)
	{
		return false;
	}
	if (r->next != NULL)
	{
		r->val = r->next->val;
		Node* t = r->next;
		r->next = r->next->next;
		free(t);
		return true;
	}
	//其它情况和下面相似
}
bool DeleteNode(int data, LinkList* list)
{
	if (*list == NULL)
	{
		return false;
	}
	Node* s = *list;
	while (s != NULL && s->next -> val != data)
	{
		s = s->next;
	}
	if (s == NULL)
	{
		return false;
	}
	Node* r = s->next;
	s->next = s->next->next;
	free(r);
	return true;
}
int main(void)
{
	LinkList list;
	Init(&list);
	Creat(&list);
	Print(list);
	//删除,根据节点删除
	Node* r = list->next->next;
	bool ret = DeleteNode(r,&list);
	//删除,根据传进去的值删除
	//bool ret = DeleteNode(4,&list);
	if (ret)
	{
		printf("删除成功\n");
	}
	else
	{
		printf("删除失败\n");
	}
	Print(list);
	return 0;
}

展开阅读全文

没有更多推荐了,返回首页