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

// 定义单链表节点结构 typedef struct Node { int data; // 数据域 struct Node* next; // 指针域 } Node;

// 创建单链表 Node* createLinkedList(int n) { Node* head = NULL; Node* tail = NULL;

for (int i = 0; i < n; i++) {
    // 创建新节点
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (newNode == NULL) {
        printf("动态内存分配失败\n");
        exit(1);
    }

    // 输入节点数据
    printf("请输入第%d个节点的值:", i + 1);
    scanf("%d", &(newNode->data));
    newNode->next = NULL;

    // 将新节点插入链表尾部
    if (head == NULL) {
        head = newNode;
        tail = newNode;
    } else {
        tail->next = newNode;
        tail = newNode;
    }
}

return head;

}

// 插入节点 Node* insertNode(Node* head, int position, int data) { Node* newNode = (Node*)malloc(sizeof(Node)); if (newNode == NULL) { printf("动态内存分配失败\n"); exit(1); } newNode->data = data;

// 插入到链表头部
if (position == 1) {
    newNode->next = head;
    head = newNode;
} else {
    Node* p = head;
    int count = 1;
    while (count < position - 1 && p != NULL) {
        p = p->next;
        count++;
    }
    if (p == NULL) {
        printf("插入位置无效\n");
        exit(1);
    }
    newNode->next = p->next;
    p->next = newNode;
}

return head;

}

// 删除节点 Node* deleteNode(Node* head, int position) { if (head == NULL) { printf("链表为空,无法删除节点\n"); exit(1); }

// 删除链表头部节点
if (position == 1) {
    Node* temp = head;
    head = head->next;
    free(temp);
} else {
    Node* p = head;
    int count = 1;
    while (count < position - 1 && p != NULL) {
        p = p->next;
        count++;
    }
    if (p == NULL || p->next == NULL) {
        printf("删除位置无效\n");
        exit(1);
    }
    Node* temp = p->next;
    p->next = p->next->next;
    free(temp);
}

return head;

}

// 取元素 int getElement(Node* head, int position) { Node* p = head; int count = 1; while (count < position && p != NULL) { p = p->next; count++; } if (p == NULL) { printf("取元素位置无效\n"); exit(1); }

return p->data;

}

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

int main() { int n; printf("请输入链表长度:"); scanf("%d", &n);

// 创建链表
Node* head = createLinkedList(n);

// 打印链表
printf("创建的链表为:");
printLinkedList(head);

// 插入节点
int insertPosition, insertData;
printf("请输入要插入的节点位置和值:");
scanf("%d %d", &insertPosition, &insertData);
head = insertNode(head, insertPosition, insertData);
printf("插入节点后的链表为:");
printLinkedList(head);

// 删除节点
int deletePosition;
printf("请输入要删除的节点位置:");
scanf("%d", &deletePosition);
head = deleteNode(head, deletePosition);
printf("删除节点后的链表为:");
printLinkedList(head);

// 取元素
int getPosition;
printf("请输入要取元素的位置:");
scanf("%d", &getPosition);
int element = getElement(head, getPosition);
printf("取得的元素为:%d\n", element);

return 0;

}

C语言实现单链表操作:插入、删除、取元素

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

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