单链表,删除其中结点为x的结点
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}Lnode;
// 非递归
// Lnode *del(Lnode *head,int data)
// {
// Lnode *p,*q;
// p=head;
// q=p;
// p=p->next;
// while(p!=NULL)
// {
// if(p->data==data)
// {
// q->next=p->next;
// p=q;
// }
// q=p;
// p=p->next;
// }
// return head;
// }
//递归
Lnode* del(Lnode *&L,int x)
{
Lnode *p ;
if(L==NULL)return NULL;
if(L->data==x)
{
p=L;
L=L->next;
free(p);
del(L,x);
}
else
{
del(L->next,x);
}
return L;
}
int main()
{
Lnode *head,*p,*s;
head=(Lnode*)malloc(sizeof(Lnode));
head->data=0;
p=head;
for(int i=1;i<10;i++)
{
Lnode *s=(Lnode*)malloc(sizeof(Lnode));
s->data=i;
p->next=s;
p=s;
}
//head=head->next;
p->next=NULL;
s=del(head,4);
while(s!=NULL)
{
cout<<s->data<<endl;
s=s->next;
}
return 0;
}
测试:0 1 2 3 4 5 6 7 8 9
删除 4
输出:0 1 2 3 5 6 7 8 9
本文介绍了一种使用递归方法删除单链表中特定值节点的算法实现。通过递归函数,可以有效地遍历链表并移除值为x的所有节点,最后返回更新后的链表头。代码示例展示了如何创建链表、调用删除函数以及打印结果链表。
c++&spm=1001.2101.3001.5002&articleId=103259873&d=1&t=3&u=ff3c73c4e02549f485f3b04d00967819)
8090

被折叠的 条评论
为什么被折叠?



