【问题标题】:Delete N nodes after M nodes in Linked list L删除链表L中M个节点后的N个节点
【发布时间】:2021-10-20 04:03:04
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
struct Node
{
    int data;
    struct Node* next;
};
void push(struct Node** head, int new)
{
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new;
    new_node->next = (*head);
    (*head) = new_node;
}
void printList(struct Node* head)
{
    struct Node* temp = head;
    while (temp != NULL)
    {
        printf("%d->", temp->data);
        temp = temp->next;
    }
}
void retainMdeleteN(struct Node* head, int M, int N)
{
    struct Node *curr = head, *t;
    int x;
    while (curr)
    {
        if (curr == NULL)
            return;
        for (x = 1; x < M; x++)
            curr = curr->next;
        t = curr->next;
        if (t != NULL)
        {
            for (x = 1; x <= N; x++)
            {
                struct Node* temp = t;
                t = t->next;
                free(temp);
            }
        }
        curr->next = t;
        curr = t;
    }
}
int main()
{
    int M, N, arr[100];
    printf("M=");
    scanf("%d", &M);
    printf("N=");
    scanf("%d", &N);
    struct Node* head = NULL;
    int n;
    printf("No.of nodes in the linked link:");
    scanf("%d", &n);
    printf("Enter the elements of the node\n");
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }
    for (int i = n - 1; i >= 0; i--)
    {
        push(&head, arr[i]);
    }
    printf("Given Linked list is :\n");
    printList(head);
    retainMdeleteN(head, M, N);
    printf("\nLinked list after deletion is :\n");
    printList(head);
    return 0;
}

它适用于大多数输入,除了 M=2 和 N=1,L=1->2->3->4->5->6->7->8->9->10。它显示信号:此特定输入的分段错误(核心转储)和剩余任何类型输入的正确答案。为什么它不为那个特定的执行?或者可能存在未执行的特定类型。

【问题讨论】:

    标签: c linked-list


    【解决方案1】:

    It is working fine for me 因为 N 和 M 更像是计数器而不是指针。

    虽然我建议在 main 中添加对 n>M 的检查并多次调用 free() 也会导致堆内的双重缓存,从而导致函数中止。也许使用 realloc(ptr,0) 而不是 free()。

    【讨论】:

    • 我在代码中哪里使用了 free()?我无法理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2013-03-25
    • 1970-01-01
    相关资源
    最近更新 更多