开卷&&有益 2021-10-13 20:57 采纳率: 80%
浏览 45
已结题

单链表删除模块 无法正常运行


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

struct student{
    char name[10];
    struct student *next;
};

void list(struct student *p)
{
        while(1){
        printf("%s \n", p->name  );
        if(p->next != NULL){
            p = p->next;
        }
        else{
            break;
        }
    }
}

struct student *create()
{
    struct student *head ,*current ,*next;
    char str[10];
    char flag;
    
    printf("输入名字:\n");
    scanf("%s", str);
    getchar();
    
    head = ((struct student *)malloc(sizeof(struct student)));
    strcpy(head->name , str);
    
    current = head;
    
    printf("是否继续输入:");
    scanf("%c", &flag);
    
    while(flag != 'N')
    {
        printf("输入你的name:\n");
        scanf("%s", str);
        getchar();
        
        next = ((struct student *)malloc(sizeof(struct student)));
        strcpy(next->name , str);
        
        current->next= next;
        
        current = next;
        
        printf("是否继续输入,N 结束:");
        scanf("%c", &flag);
    } 
    // 循环结束,当前指针指向最后一个元素,此时将最后一个元素的指针赋值为NULL
    current->next = NULL; 
    return head;
}


struct student * de(struct student *p)
{
    struct student *current, *temp;
    current = p;
    int position;
    printf("输入要删除的位置:");
    scanf("%d", &position);
    if(position==1)
    {
        p = current->next;
        free(current);
    }
    else if(1)
    {
        for(int i = 1;i <= position-1;i ++)
    {
        current = current->next ;
    }
    temp = current->next;
    current->next = temp->next;
    free(temp);
    
    }
    list(p);
}

int main()
{
    
    struct student *p;
    p = create();
    printf("当前列表为:\n"); 
    list(p);
    while(1)
    {
    de(p);
    
    }
    return 0;
}

```希望大佬能帮忙改一下,改了几天了,初学,想实现删除第n个元素的代码,就改一下删除模块就OK

```

  • 写回答

1条回答 默认 最新

  • CSDN专家-link 2021-10-13 21:02
    关注

    删除函数没有return语句。如果删除第一个就不行了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 10月21日
  • 已采纳回答 10月13日
  • 创建了问题 10月13日