整体结构如上:看似简单,但第一次用C语言实现还是感觉有点吃力,尤其是特别容易让链表断裂
下面是代码:(有链表的增删改查)
注:这里E类型是用define将int进行了宏定义
cpp
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#define E int//以后想改元素类型就在这里该就行
typedef struct node {
E element;//元素
struct node* next;//下一节点的指针
}node;
void initialise_node(node* head) {
head->next = NULL;//初始化头节点
}
int add_node(node* head,E ele,int index) {
node* tem = head;//拷贝一份head,以后在tem上进行修改
if (index < 1) return -1;//插入要位置大于0
while (--index) {
tem = tem->next;
if (tem == NULL)return -1;
}
node* ptr = (node*)malloc(sizeof(node));
ptr->next = NULL;
if (ptr == NULL) {//开辟内存失败情况
perror("malloc");
return -1;
}
ptr->element = ele;
ptr->next = tem->next;
tem->next = ptr;
return 1;
}
/// <summary>
/// 删除所有是ele的元素
/// </summary>
/// <param name="head">头节点指针</param>
/// <param name="ele">元素</param>
/// <returns></returns>
int del_node(node* head, E ele) {
node* tem = NULL;
while (1) {
if (head->next == NULL) return 2;
tem = head->next;//头节点移动
if (tem->element == ele) {
if (tem->next == NULL) {//找到的节点下一节点为空的情况
free(tem);
head->next = NULL;
return 1;
}
head->next=tem->next;
free(tem);
}
head = head->next;
}
}
/// <summary>
/// 找出所有元素,并返回这个节点地址,如有需要返回多个可以创建一个数组
/// </summary>
/// <param name="head">头节点地址</param>
/// <param name="ele">要找的元素</param>
/// <returns></returns>
node* find_node(node* head, E ele) {
head = head->next;//先让头节点移动一次
while (head != NULL) {
if (head->element == ele) {
return head;
}
head = head->next;
}
}
node* modify_node(node* head, int index, E ele) {
head = head->next;//头节点指针先移动一次
if (index < 1)return -1;
while (--index && head != NULL) {
head = head->next;
}
if (head == NULL)return -1;
head->element = ele;
return head;//返回这个元素的地址
}
//通过第几个数字找到元素
int del_node_byindex(node* head,int index) {
node* tem = head->next;
if (index < 1)return -1;
while (--index && tem != NULL) {
head = tem;
tem = tem->next;//移动节点
}
if (tem == NULL)return -1;
//删除节点
head->next = tem->next;
free(tem);
tem = NULL;
}
void print_node(node* head) {
node* tem = head;
while (tem->next!=NULL) {
tem = tem->next;
printf("%d\n", tem->element);
}
}
int main() {
node head;
initialise_node(&head);
for (int i = 1; i <= 8; i++) {
add_node(&head, 20 * i, i);
}
add_node(&head, 20, 9);
printf("%d\n", del_node(&head, 20));
node* find = find_node(&head, 160);
printf("%d\n", find->element);
printf("---------------\n");
print_node(&head);
printf("---------------\n");
del_node_byindex(&head, 9);
print_node(&head);
printf("---------------\n");
modify_node(&head, 3, 520);
print_node(&head);
return 0;
}