关于链表操作的问题,如何解决?

img


#include
using namespace std;
#pragma GCC optimize(2)
struct ListNode {
    int value;
    ListNode* next;
    ListNode(int val) :value(val), next(NULL) {};
    ListNode() :value(0), next(NULL) {};
};

void _insert(ListNode* head, int pos, int value) {
    ListNode* pre = head, * cur = head;

    for (int i = 0; i <= pos; ++i) {
        pre = cur;
        cur = cur->next;
    }

    ListNode* to_insert = new ListNode(value);
    pre->next = to_insert;
    to_insert->next = cur;
}

void _delete(ListNode* head, int pos) {
    ListNode* pre = head, * cur = head;

    for (int i = 1; i <= pos; ++i) {
        pre = cur;
        cur = cur->next;
    }
    pre->next = cur->next;
    cur = cur->next;
}

int main() {
    int n, m;
    scanf("%d %d", &n, &m);

    ListNode* head = new ListNode(),*cur = head;

    for (int i = 0; i < n; i++) {
        int t;
        cin >> t;
        ListNode* tmp = new ListNode(t);
        cur->next = tmp;
        cur = cur->next;
    }

    int c;
    for (int i = 0; i < m; ++i) {
        cin >> c;

        if (c == 1) {
            int insert_value,pos;
            scanf("%d %d", &pos, &insert_value);
            _insert(head, pos, insert_value);
        }
        else {
            int pos;
            cin >> pos;
            _delete(head, pos);
        }
    }

    ListNode* p = head->next;

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

    return 0;
}

AC后是错的

建议看我博客,满意求个采纳
https://blog.csdn.net/fyzxl/article/details/127362836?spm=1001.2014.3001.5502

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^