编辑代码

#include <stdio.h>
#include "windows.h"

typedef int E;

// 链表的结构体
struct ListNode {
    E element; //元素位置
    struct ListNode *Next; //指针
};
typedef struct ListNode *Node;

//初始化链表 head节点不存数据
void initList(Node node) {
    node->Next = NULL;
}

// 插入方法
BOOL insetList(Node head, E element, int index) {
    if (index < 0) return 0;
    index++;
    // 通过一个一个指针 找到插入前的头节点
    while (--index) {
        head = head->Next;
        if (head->Next == NULL) return 0;
    }
    // malloc 动态分配内存 struct ListNode* node 接收
    Node node = malloc(sizeof(struct ListNode));
    if (node == NULL) return 0;
    node->element = element;
    node->Next = head->Next;
    head->Next = node;
    return 1;
}

// 删除方法
BOOL delList(Node head, int index) {
    if (index < 0) return 0;
    index++;
    // 寻找目标head
    while (--index) {
        head = head->Next;
        if (head->Next == NULL) return 0;
    }
    //判断删除index处值合法性
    if (head->Next == NULL) return 0;
    //删除操作
    Node tmp = head->Next;
    head->Next = head->Next->Next;
    free(tmp);
    return 1;

}

// get元素指针
E *getList(Node head, int index) {
    // 判断index合法性
    if (index < 0) return NULL;
    index++;
    //遍历 index处head值
    do {
        if (head->Next == NULL)return NULL;
        head = head->Next;
    } while (--index);
    // 返回index处 head->element的指针
    return &head->element;
}

// 找到链表中的相应元素的index值
int findList(Node head, E element) {
    int index = 0;
    //do while循环 两个分区变量互相独立
    do {
        head = head->Next;
        if (head->element == element) return index;
        if (head->Next == NULL) return -1;
        index++;
    } while (1);
}

//遍历方法
void f(Node head) {
    do {
        if (head->Next == NULL) {
            printf("\n");
            return;
        }
        head = head->Next;
        printf("%d ", head->element);
    } while (1);
}

//test
int main() {
    struct ListNode head;
    initList(&head);
    for (int i = 1; i < 6; ++i) {
        insetList(&head, i * 100, 0);
    }
    f(&head);
    delList(&head, 3);
    f(&head);
    int a = *getList(&head, 3);
    printf("%d\n", a);
    a = findList(&head, 100);
    printf("%d\n", a);


};