头文件
#ifndef CPROJECT_LINK_H
#define CPROJECT_LINK_H
#include <stdlib.h>
#include <stdio.h>
typedef int data_t;
typedef struct node{
data_t data;
struct node *next;
}node_t;
node_t *node_init();
void node_insert_behind(node_t *p, node_t *node);
void node_head_insert(node_t *p, data_t x);
void node_tail_insert(node_t *p, data_t x);
void node_delete(node_t *p, data_t x);
void node_update(node_t *p, data_t old, data_t new);
void node_show(node_t *p);
#endif //CPROJECT_LINK_H
实现文件
#include "../header/link.h"
node_t *node_init(){
node_t *node = (node_t *) malloc(sizeof(node_t));
if(node == NULL){
perror("malloc");
return NULL;
}
node->next = NULL;
return node;
}
void node_insert_behind(node_t *p, node_t *node){
node->next = p->next;
p->next = node;
}
void node_head_insert(node_t *p, data_t x){
node_t *node = node_init();
node->data = x;
node_insert_behind(p,node);
}
void node_tail_insert(node_t *p, data_t x){
while (p->next != NULL)
p = p->next;
node_t *node = node_init();
node->data = x;
node_insert_behind(p,node);
}
void node_delete(node_t *p, data_t x){
node_t *node = NULL;
while (p->next != NULL){
node = p->next;
if(node->data == x){
p->next = node->next;
node->next = NULL;
free(node);
} else{
p = p->next;
}
}
}
void node_update(node_t *p, data_t old, data_t new){
node_t *node = NULL;
node_t *new_node = NULL;
while (p->next != NULL){
node = p->next;
if(node->data == old){
new_node = node_init();
new_node->data = new;
new_node->next = node->next;
p->next = new_node;
node->next = NULL;
free(node);
}
p = p->next;
}
}
void node_show(node_t *p){
while (p->next != NULL){
printf("%d ",p->next->data);
p = p->next;
}
printf("\n");
}
测试文件
#include "../header/link.h"
int main(){
node_t *p = node_init();
for (int i = 0; i < 5; ++i) {
node_head_insert(p, i);
node_tail_insert(p, i);
}
node_show(p);
printf("*******************************\n");
node_delete(p,0);
node_show(p);
printf("*******************************\n");
node_update(p,2,100);
node_show(p);
return 0;
}