首页 > 数据结构栈删除报错

数据结构栈删除报错

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

void insert();
void delete();
void display();
void quit();

struct student
{
                int id;
                int score;
                struct student *next;
};

struct student *x, *head, *current;

int main()
{
        /*链表的第一个节点不存放数据*/
        head = (struct student *) malloc(sizeof(struct student));
        head->next = NULL;
        for( ; ; ) {
                int a;
                printf("\n");
                printf("1)insert\n2)delete\n3)display\n4)quit\n");
                printf("which one: ");
                scanf("%d", &a);
                printf("\n");
                switch(a)
                {
                        case 1:
                                insert();
                                break;
                        case 2:
                                delete();
                                break;
                        case 3:
                                display();
                                break;
                        case 4:
                                quit();
                                break;
                }
        }
        printf("\n\n~~~~~~~~~~~~~~~FINSH~~~~~~~~~~~~~~");
        return 0;
}

void insert()
{
        x = (struct student *) malloc(sizeof(struct student));
        printf("please input your id : ");
        scanf("%d", &x->id);
        printf("please input your score : ");
        scanf("%d", &x->score);
        x->next = NULL;

        x->next = head->next;
        head->next = x;
        printf("====================================\n");
}

void delete()
{
        char ch;
        if (head->next == NULL)
        {
                printf("the linked list is empty!\n");
                return ;
        }
        printf ("are you sure (y/n)? ");
        scanf("%s", ch);

        if (tolower(ch) == 'y')
        {
                current = head->next;
                printf("\n%d record has been deleted!!!", current->id);
                head->next = current->next;
                free(current);
        }
        printf("\n=================================\n");
}
void display()
{
        if (head->next == NULL)
                printf ("the linked list is empty!\n");
        else
        {

                current = head->next;
                while (current != NULL)
                {
                        printf("id:%d, score=%d\n", current->id, current->score);
                        current = current->next;
                }
        }
        printf("==================================\n");
}

void quit()
{
        exit(0);
}

输出情况:

$ ./a.out

1)insert
2)delete
3)display
4)quit
which one: 1

please input your id : 1
please input your score : 1
====================================

1)insert
2)delete
3)display
4)quit
which one: 2

are you sure (y/n)? y
Segmentation fault

scanf("%s", ch);

改成scanf("%s", &ch);

【热门文章】
【热门文章】