- 已知一个单向链表的头,请写出删除其某一个结点的算法,要求,先找到此
结点,然后删除。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
//27. 已知一个单向链表的头,请写出删除其某一个结点的算法,要求,先找到此
//结点,然后删除。
typedef struct listnode
{
int val;
struct listnode* next;
};
int main()
{
listnode* head, *tail;
head = (listnode*)malloc(sizeof(listnode));//开辟头结点的新地址
tail = head;
head->next = nullptr;
//创建10个新结点
int i = 1;
for (i = 1; i < 11; i++)
{
listnode *newnode;
//创建新结点的空间
newnode = (listnode*)malloc(sizeof(listnode));
newnode->val = i;
newnode->next = nullptr;
tail->next = newnode;//把newnode接到head的后面
tail = newnode;//把游标tail移动到newnode上
}
//打印创建的结点
listnode* phead = head->next;
while (phead!= nullptr)
{
printf("%d->", phead->val);
phead = phead->next;
}
printf("\n");
//删除指点结点
listnode* pre = head;
phead = head->next;
while (phead != nullptr)
{
/*printf("%d->", phead->val);*/
if (phead->val == 5)
{
pre->next = phead->next;
free(phead);
break;
}
phead = phead->next;
pre = pre->next;
}
phead = head->next;
while (phead != nullptr)
{
printf("%d->", phead->val);
phead = phead->next;
}
return 0;
}
![](https://img-blog.csdnimg.cn/aa340ed5b0374609b8f3267396fd0577.png)