【作业day4】

1. 单向链表

#include 
#include 

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

struct LinkedList {
    struct Node* head;
};

void addNode(struct LinkedList* list, int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;

    if (list->head == NULL) {
        list->head = newNode;
    } else {
        struct Node* current = list->head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

void removeNode(struct LinkedList* list, int targetData) {
    struct Node* current = list->head;
    struct Node* prev = NULL;

    while (current != NULL && current->data != targetData) {
        prev = current;
        current = current->next;
    }

    if (current == NULL) {
        return;
    }

    if (prev != NULL) {
        prev->next = current->next;
    } else {
        list->head = current->next;
    }

    free(current);
}

2.双向链表

#include 
#include 

struct Node {
    int data;
    struct Node* prev;
    struct Node* next;
};

struct DoublyLinkedList {
    struct Node* head;
};

void addNode(struct DoublyLinkedList* list, int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->prev = NULL;
    newNode->next = NULL;

    if (list->head == NULL) {
        list->head = newNode;
    } else {
        struct Node* current = list->head;
        while (current->next != NULL) {
            current = current->next;
        }
        newNode->prev = current;
        current->next = newNode;
    }
}

void removeNode(struct DoublyLinkedList* list, int targetData) {
    struct Node* current = list->head;

    while (current != NULL && current->data != targetData) {
        current = current->next;
    }

    if (current == NULL) {
        return;
    }

    if (current->prev != NULL) {
        current->prev->next = current->next;
    } else {
        list->head = current->next;
    }

    if (current->next != NULL) {
        current->next->prev = current->prev;
    }

    free(current);
}

你可能感兴趣的:(数据结构)