数据结构-单链表

162 阅读1分钟

感谢UP主[TyrantLucifer]分享的视频,参考B站www.bilibili.com/video/BV1W6…

#include <stdio.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0

/*
    头节点的data存储链表长度

*/
typedef struct Node {
    int data;
    struct Node* next;
}Node;

Node* initList() {
    Node* L = (Node*)malloc(sizeof(Node));
    L->data = 0;
    L->next = NULL;
    return L;
}

void headInsert(Node* L, int data) {
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->next = L->next;
    L->next = node;
    L->data++;
}

void tailInsert(Node* L, int data) {
    Node* node = L;
    for (int i = 0; i < L->data; i++) {
        node = node->next;
    }
    Node* n = (Node*)malloc(sizeof(Node));
    n->data = data;
    n->next = NULL;
    node->next = n;
    L->data++;
}

int delete(Node* L, int data) {
    Node* node = L->next;
    Node* pre = L;
    while (node) {
        if (node->data == data) {
            pre->next = node->next;
            free(node);
            printf("success del\n");
            return TRUE;
        }
        pre = node;
        node = node->next;
    }
    printf("fail del\n");
    return FALSE;
}
void printList(Node* L) {
    Node* node = L->next;
    while (node) {
        printf("node = %d\n", node->data);
        node = node->next;
    }
}

int main()
{
    Node* L = initList();
    headInsert(L, 1);
    headInsert(L, 2);
    headInsert(L, 3);
    headInsert(L, 4);
    headInsert(L, 5);
    tailInsert(L, 6);
    tailInsert(L, 7);
    printList(L);
    delete(L, 3);
    printList(L);
    return 0;
}