m0_64018569 2021-11-13 21:13 采纳率: 78.6%
浏览 107
已结题

线性表插入删除,写代码

编写函数,长度最大为20个整型元素的线性表,插入、删除整数,没插入或删除一次后显示出变化后的线性表,在主函数中调用实现

  • 写回答

1条回答 默认 最新

  • 关注

    代码如下

    #include <stdio.h>
    #include <stdlib.h>
    struct StNode 
    {
        int data;
        struct StNode* next;
    };
    
    struct StNode* CreateList()
    {
        int i,n;
        struct StNode* head,*p,*t;
        head = (struct StNode*)malloc(sizeof(StNode));
        head->next = NULL;
        t = head;
        printf("请输入链表的长度:");
        scanf("%d",&n);
        printf("请输入链表数据:");
        for (i=0;i<n;i++)
        {
            p = (struct StNode*)malloc(sizeof(StNode));
            scanf("%d",&(p->data));
            p->next = NULL;
            t->next = p;
            t = p;
        }
        return head;
    }
    //插入
    struct StNode* InsertList(struct StNode*head,int pos,int data)
    {
        struct StNode* p = head,*t;
        int i=1;
        while(i<pos && p)
        {
            p = p->next;
            i++;
        }
        if (p)
        {
            t = (struct StNode*)malloc(sizeof(StNode));
            t->data = data;
            t->next = p->next;
            p->next = t;
            printf("插入成功\n");
        }else
            printf("插入位置不合适,插入失败\n");
        
        return head;
    }
    
    //删除
    struct StNode* Delete(struct StNode* head,int pos)
    {
        int i = 1;
        struct StNode* p = head,*t;
        while(i<pos && p)
        {
            p = p->next;
            i++;
        }
        if (p)
        {
            t = p->next;
            p->next = t->next;
            free(t);
            t = 0;
            printf("删除成功\n");
        }else
            printf("删除成功\n");
        return head;
    }
    
    
    //显示
    void show(struct StNode* head)
    {
        struct StNode* p = head->next;
        while(p)
        {
            printf("%d ",p->data);
            p = p->next;
        }
        printf("\n");
    }
    
    //释放空间
    void Free(struct StNode* head)
    {
        struct StNode* p;
        while(head)
        {
            p = head->next;
            free(head);
            head = p;
        }
        head = 0;
    }
    
    
    int main()
    {
        int pos,data;
        struct StNode* head = CreateList();
        show(head);
    
        //插入
        printf("请输入插入位置(从1开始)和数据:");
        scanf("%d %d",&pos,&data);
        head = InsertList(head,pos,data);
        printf("插入后链表数据:");
        show(head);
    
        //删除
        printf("请输入删除位置(从1开始):");
        scanf("%d",&pos);
        head = Delete(head,pos);
        printf("删除后链表数据:");
        show(head);
    
        //释放空间
        Free(head);
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 11月22日
  • 已采纳回答 11月14日
  • 创建了问题 11月13日