C语言实现链表删除最大值节点

以下是使用C语言编写的等效代码:

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

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

struct Node* createNode(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->value = value;
    newNode->next = NULL;
    return newNode;
}

struct Node* deleteMaxNode(struct Node* head) {
    if (head == NULL) {
        return NULL;
    }

    if (head->next == NULL) {
        return NULL;
    }

    int maxValue = head->value;
    struct Node* maxPrev = NULL;
    struct Node* current = head;

    while (current->next != NULL) {
        if (current->next->value > maxValue) {
            maxValue = current->next->value;
            maxPrev = current;
        }
        current = current->next;
    }

    if (maxPrev != NULL) {
        struct Node* temp = maxPrev->next;
        maxPrev->next = temp->next;
        free(temp);
    } else {
        struct Node* temp = head;
        head = head->next;
        free(temp);
    }

    return head;
}

void printLinkedList(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        printf('%d ', current->value);
        current = current->next;
    }
    printf('\n');
}

int main() {
    struct Node* head = NULL;
    struct Node* current = NULL;
    int value;

    while (scanf('%d', &value) != EOF) {
        if (value == -1) {
            break;
        }

        struct Node* newNode = createNode(value);

        if (head == NULL) {
            head = newNode;
            current = newNode;
        } else {
            current->next = newNode;
            current = newNode;
        }
    }

    head = deleteMaxNode(head);

    printLinkedList(head);

    return 0;
}

这段C代码可以读取以空格分隔的正整数输入,并以-1作为结束符。然后,它将输出删除最大值结点后的链表。

代码功能说明:

  1. 创建节点: createNode 函数用于创建一个新的节点,并初始化其值和指向下一个节点的指针。
  2. 删除最大值节点: deleteMaxNode 函数用于遍历链表,找到最大值节点,并将其从链表中删除。该函数首先判断链表是否为空,然后遍历链表,找到最大值节点和其前一个节点,最后将最大值节点从链表中移除。
  3. 打印链表: printLinkedList 函数用于打印链表中的所有节点。
  4. 主函数: main 函数用于读取用户输入,构建链表,调用 deleteMaxNode 函数删除最大值节点,并调用 printLinkedList 函数打印结果链表。

总结:

这段代码演示了使用C语言实现链表操作的基本方法,包括节点的创建、插入、删除和遍历等操作。通过理解这段代码,您可以学习如何使用C语言进行链表操作,并将其应用于其他数据结构和算法中。

C语言实现链表删除最大值节点

原文地址: https://www.cveoy.top/t/topic/FCH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录