*单链表的创建,打印,释放,删除指定节点
直接看代码
(菜鸟创作,技术太菜,不喜勿喷,谢谢)
struct cell { //单链表结点结构体定义
int x;
struct cell* next;
};
创建单链表
struct cell* build(void) { //新建单链表,并将建好的单链表首结点地址返回
struct cell* head,*tmp,*p;
head = tmp = p = NULL;
int n;
scanf("%d",&n);
if(n==0)//输入的数据以0结束
return head;
else{
p=(struct cell*)malloc(sizeof(struct cell));
head=p;
p->x=n;
p->next=NULL;
tmp=p;
scanf("%d",&n);
while(n!=0){
p=(struct cell*)malloc(sizeof(struct cell));
p->next=NULL;
p->x=n;
tmp->next=p;
tmp=p;
scanf("%d",&n);
}
}
return head;
//返回单链表头
}
打印单链表
void print(struct cell* head) {//打印整个单链表,head是指向单链表首结点的指针
struct cell * ph=head;
if(ph==NULL){
printf("NULL");
return; }
else{
printf("%d",ph->x);
ph=ph->next;
while(ph!=NULL){
printf("%d",ph->x);//自己选择是否加空格
ph=ph->next;
}
}
}
**
释放空间
**
```void print(struct cell* head) {//打印整个单链表,head是指向单链表首结点的指针
struct cell * ph=head;
if(ph==NULL){
printf("NULL");
return; }
else{
printf("%d",ph->x);
ph=ph->next;
while(ph!=NULL){
printf("%d",ph->x);//自己选择是否加空格
ph=ph->next;
}
}
}
删除链表中指定节点
void del(struct cell**head,int m){
struct cell *p=*head,*p1=*head;
if(head==NULL)
return ;
while(p!=NULL){
if(p->x==m){
if(p==*head){
*head=p->next;
}
struct cell* t=p;
p1->next=p->next;
p=p->next;
free(t);
}
else{
p1=p;
p=p->next;
}
}
}
来看看题目
完整代码
#include <stdio.h>
#include <malloc.h>
struct cell { //单链表结点结构体定义
int x;
struct cell* next;
};
struct cell* build(void) { //新建单链表,并将建好的单链表首结点地址返回
struct cell* head,*tmp,*p;
head = tmp = p = NULL;
int n;
scanf("%d",&n);
if(n==0)
return head;
else{
p=(struct cell*)malloc(sizeof(struct cell));
head=p;
p->x=n;
p->next=NULL;
tmp=p;
scanf("%d",&n);
while(n!=0){
p=(struct cell*)malloc(sizeof(struct cell));
p->next=NULL;
p->x=n;
tmp->next=p;
tmp=p;
scanf("%d",&n);
}
}
return head;
//返回单链表头
}
void print(struct cell* head) {//打印整个单链表,head是指向单链表首结点的指针
struct cell * ph=head;
if(ph==NULL){
printf("NULL");
return; }
else{
printf("%d",ph->x);
ph=ph->next;
while(ph!=NULL){
printf("%d",ph->x);//自己选择是否加空格
ph=ph->next;
}
}
}
void release(struct cell* head) {//释放单链表空间,head是指向单链表首结点的指针
struct cell*p1;
while(head!=NULL){
p1=head;
head=p1->next;
free(p1);
}
}
void del(struct cell**head,int m){
struct cell *p=*head,*p1=*head;
if(head==NULL)
return ;
while(p!=NULL){
if(p->x==m){
if(p==*head){
*head=p->next;
}
struct cell* t=p;
p1->next=p->next;
p=p->next;
free(t);
}
else{
p1=p;
p=p->next;
}
}
}
int main(void) {
struct cell* phead;
int key;
phead = build();//创建链表
scanf("%d",&key);
del(&phead,key);//删除元素
if(phead!=NULL)
print(phead);
else
printf("NULL");
release(phead);
}
欢迎提出改进建议!谢谢!