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

#include<stdio.h>
#include<malloc.h>
//删除单链表中的任意一个节点，可能是传节点删除，也可能是传节点的值删除
typedef struct _Node
{
int val;
struct _Node* next;
//不带头结点的单链表
{
(*list) = NULL;
}
{
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);
}
}
{
Node* r = list;
while (r != NULL)
{
printf("%d ", r->val);
r = r->next;
}
printf("\n");
}
/*
{
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;
}
*/
//根据节点删除，还有一种方法就是，把它下一个节点的数据给它自己，然后删除它的下一个节点
{
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;
}
//其它情况和下面相似
}
{
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)
{
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;
}