视频讲解(献丑了):p40 第1题 王道数据结构课后代码题c语言代码实现_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1Xa4y1Q7ui/?spm_id_from=333.999.0.0
首先它是一个不带头结点的单链表
我们就得特殊处理
我们先让*L==NULL;
然后为s开辟一个新的存储空间,让他等于a[0]的值
下面我们看一下建立无头节点的单链表代码该如何实现
void buildlinklist(linklist* L)
{*L = NULL;lnode* s, * r = *L;int i = 0;if (*L == NULL){s = (lnode*)malloc(sizeof(lnode));s->data = a[0];s->next = NULL;*L = s;}r = *L;for (i = 1; i < n; i++){s = (lnode*)malloc(sizeof(lnode));s->data = a[i];r->next = s;r =s;}r->next = NULL;
}
递归的图解
本题主要代码为
void delete(linklist* L,int x)
{lnode* p;if (*L== NULL) {return;}if((*L)->data == x) {p = *L;*L = (*L)->next;free(p);delete(L, x);}else {delete(&(*L)->next, x);}
}
完整测试代码为
#include<stdio.h>
#include<stdlib.h>
typedef struct lnode
{int data;struct lnode* next;
} lnode, * linklist;
int a[5] = { 1,3,3,4,5 };
int n = 5;
void buildlinklist(linklist* L)
{*L = NULL;lnode* s, * r = *L;int i = 0;if (*L == NULL){s = (lnode*)malloc(sizeof(lnode));s->data = a[0];s->next = NULL;*L = s;}r = *L;for (i = 1; i < n; i++){s = (lnode*)malloc(sizeof(lnode));s->data = a[i];r->next = s;r =s;}r->next = NULL;
}
void delete(linklist* L,int x)
{lnode* p;if (*L== NULL) {return;}if((*L)->data == x) {p = *L;*L = (*L)->next;free(p);delete(L, x);}else {delete(&(*L)->next, x);}
}
void print(linklist* L)
{lnode* k=*L;while (k){printf("%d ", k->data);k = k->next;}
}
int main()
{linklist L;buildlinklist(&L);delete(&L,3);print(&L);
}