向单向链表中删除指定的节点
前言:从链表中删除一个节点与插入一个节点类似,关键在于查找,但需要注意的是,删除一个节点 并不是真的删除了,而是将需要删除的节点从链表中分离出来,最后将这个结点用free函数释放掉。
一、问题描述
给出一个学号,删除单向链表中学号与之相等的节点
二、算法描述
1. 输入数据;
2. 在链表中匹配该数据所对应的节点;
3. 撤销此节点原来的链接关系;
4. 释放该节点。
注意:此算法中的第二步可分为多种情况,具体如下:
三、代码部分
1. structure.h
// Structure
// Created by Lanyan on 20/07/2021.
// JiaoZuo
#ifndef _structure_h
#define _structure_h
#include "stdio.h"
struct stu{ //定义一个包含学号和成绩的结构体
int num; //数据域
float score; //数据域
struct stu *next;//指针域
};
#endif
2. delete.h
// delete a designated note
// Created by Lanyan on 22/07/2021.
// JiaoZuo
#ifndef _DELETE_H
#define _DELETE_H
#include "structure.h"
struct stu *del(struct stu *head, int m){
struct stu *p1; //point to the note to delete
struct stu *p2; //point to the precursor note to delete
if(head == NULL)
printf("the list is NULL\n"); //list is NULL
else {
p1 = head;
while((p1 != NULL) && (p1 ->num != m)){ //search
p2 = p1;
p1 = p1->next;
}
if(p1 != NULL){
if(p1 == head){
head = p1->next;
} else
p2->next = p1->next;
printf("delete successfully!\n");
free(p1);
} else
printf("there is no note to delete\n");
}
return head;
}
#endif //_DELETE_H