Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

编写单链表的基本操作函数,如初始化、访问、插入、删除、创建等函数。调用基本操作函数完成以下功能:1)创建一个单链表:从键盘读入几个整数,按输入顺序形成单链表。将创建好的链表元素依…

  1. User

    编写单链表的基本操作函数,如初始化、访问、插入、删除、创建等函数。调用基本操作函数完成以下功能:1)创建一个单链表:从键盘读入几个整数,按输入顺序形成单链表。将创建好的链表元素依次输出到屏幕上。2)在已创建好的链表中插入一个元素:从键盘读入元素值和插入位置,调用插入函数完成插入操作。然后将链表元素依次输出到屏幕上。

  2. Assistant

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

    typedef struct node{ int data; // 数据域 struct node *next; // 指针域 }Node;

    // 创建单链表 Node *CreateList(){ Node *head, *tail, *p; int num;

    head = tail = (Node*)malloc(sizeof(Node)); // 初始化头节点
    tail->next = NULL;  // 初始化为空链表
    
    printf("请输入一个整数(输入-1结束): ");
    scanf("%d", &num);
    
    while(num != -1){
        p = (Node*)malloc(sizeof(Node));
        p->data = num;
        p->next = NULL;
    
        tail->next = p;
        tail = p;
    
        printf("请输入一个整数(输入-1结束): ");
        scanf("%d", &num);
    }
    
    return head;
    

    }

    // 插入元素 Node *Insert(Node *head, int pos, int value){ Node *p, *q; int i = 0;

    p = head;
    
    // 找到插入位置
    while(p && i < pos-1){
        p = p->next;
        i++;
    }
    
    // 插入位置不合法
    if(!p || i > pos-1){
        printf("插入位置不合法!\n");
        return head;
    }
    
    // 新建插入节点
    q = (Node*)malloc(sizeof(Node));
    q->data = value;
    q->next = p->next;
    
    p->next = q;
    
    return head;
    

    }

    // 删除元素 Node *Delete(Node *head, int pos){ Node *p, *q; int i = 0;

    p = head;
    
    // 找到要删除的位置
    while(p && i < pos-1){
        p = p->next;
        i++;
    }
    
    // 要删除的位置不合法
    if(!p || !p->next || i > pos-1){
        printf("删除位置不合法!\n");
        return head;
    }
    
    // 删除节点
    q = p->next;
    p->next = q->next;
    free(q);
    
    return head;
    

    }

    // 输出链表 void PrintList(Node *head){ Node *p; p = head->next;

    while(p){
        printf("%d ", p->data);
        p = p->next;
    }
    
    printf("\n");
    

    }

    int main(){ Node *head; int pos, value;

    printf("创建链表:\n");
    head = CreateList();
    printf("链表元素为:");
    PrintList(head);
    
    printf("\n插入元素:");
    printf("\n请输入要插入的位置:");
    scanf("%d", &pos);
    printf("请输入要插入的值:");
    scanf("%d", &value);
    head = Insert(head, pos, value);
    printf("插入后链表元素为:");
    PrintList(head);
    
    printf("\n删除元素:");
    printf("\n请输入要删除的位置:");
    scanf("%d", &pos);
    head = Delete(head, pos);
    printf("删除后链表元素为:");
    PrintList(head);
    
    return 0;
    

    }