MST

星途 面试题库

面试题:C语言链表节点删除操作

请用C语言实现一个单链表,并编写一个函数用于删除指定值的节点。要求给出完整代码,包括链表的创建、节点插入和删除函数。假设链表节点结构体定义为:struct Node { int data; struct Node* next; }。
11.8万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构体
struct Node {
    int data;
    struct Node* next;
};

// 创建新节点
struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 在链表头部插入节点
void insertAtHead(struct Node** head, int data) {
    struct Node* newNode = createNode(data);
    newNode->next = *head;
    *head = newNode;
}

// 删除指定值的节点
void deleteNode(struct Node** head, int key) {
    struct Node *temp = *head, *prev;

    // 如果头节点就是要删除的节点
    if (temp != NULL && temp->data == key) {
        *head = temp->next;
        free(temp);
        return;
    }

    // 寻找要删除的节点
    while (temp != NULL && temp->data != key) {
        prev = temp;
        temp = temp->next;
    }

    // 如果找到了要删除的节点
    if (temp != NULL) {
        prev->next = temp->next;
        free(temp);
    }
}

// 打印链表
void printList(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

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

    insertAtHead(&head, 1);
    insertAtHead(&head, 2);
    insertAtHead(&head, 3);

    printf("Original list: ");
    printList(head);

    deleteNode(&head, 2);

    printf("List after deletion: ");
    printList(head);

    return 0;
}