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

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

struct Node* head = NULL;

void insert(int pos, int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    if (pos == 1) {
        newNode->next = head;
        head = newNode;
    }
    else {
        struct Node* temp = head;
        for (int i = 0; i < pos - 2; i++) {
            temp = temp->next;
        }
        newNode->next = temp->next;
        temp->next = newNode;
    }
}

void delete(int pos) {
    if (head == NULL) {
        printf("List is empty\n");
        return;
    }
    struct Node* temp = head;
    if (pos == 1) {
        head = temp->next;
        free(temp);
        return;
    }
    for (int i = 0; i < pos - 2; i++) {
        temp = temp->next;
    }
    if (temp == NULL || temp->next == NULL) {
        printf("Invalid position\n");
        return;
    }
    struct Node* toDelete = temp->next;
    temp->next = toDelete->next;
    free(toDelete);
}

void display() {
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

int main() {
    int choice, pos, data;
    while (1) {
        printf("1.Insert\n2.Delete\n3.Display\n4.Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        switch (choice) {
            case 1:
                printf("Enter position and data to insert: ");
                scanf("%d %d", &pos, &data);
                insert(pos, data);
                break;
            case 2:
                printf("Enter position to delete: ");
                scanf("%d", &pos);
                delete(pos);
                break;
            case 3:
                display();
                break;
            case 4:
                exit(0);
            default:
                printf("Invalid choice\n");
        }
    }
    return 0;
}
``
创建c语言程序。程序实现如下功能1创建链表2链表的插入输入要插入结点在链表中位置然后输入插入元素恢复为一个链表;3链表的删除输入要删除结点在链表中位置然后从链表中删除该结点。4显示该链表。5退出程序。

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

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