weixin_45856506
G71260
2019-11-08 22:51
采纳率: 100%
浏览 332

c语言构建单向链表,vs正常运行但是gcc会报错runtime error:segmentation fault。

已解决,加上对空指针的判断即可通过编译。//下方代码未改正

#include <stdio.h>
#include <stdlib.h>
main()
{
    typedef struct a {
        int val;
        struct a* next;
    } link;
    link* head, * node, * end, * current;
    head = (link*)malloc(sizeof(link));
    end = head;
    int n, m, i;
    scanf("%d %d", &n, &m);
    for (i = 0; i <= n; i++) {
        node = (link*)malloc(sizeof(link));
        node->val = i + 1;
        end->next = node;
        end = node;
    }
    end->val = 1;
    end->next = NULL;
    current = head->next;
    getchar();
    while (m--) {
        char c = getchar();
        if (c == 'M') {
            scanf("%d", &i);
            while (i--&& current!=NULL)current = current->next;
        }
        if (c == 'I') {
            scanf("%d", &i);
            node = (link*)malloc(sizeof(link));
            node->next = current->next;
            node->val = i;
            current->next = node;
        }
        if (c == 'R'&& current->next!=NULL) {
            node = current->next;
            current->next = node->next;
            free(node);
        }
        if (c == 'P'&& current!=NULL)printf("%d\n", current->val);
        getchar();
    }

    for (current = head; node != NULL;) {
        node = current->next;
        free(current);
        current = node;
    }free(current);
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

相关推荐