我正在使用 C 中的双向链表,并且我正在使用 Turbo C++,但编译器正在占用两个额外的节点而不添加

I am Working with Doubly Linked Lists in C and I am Using Turbo C++ but The Compiler is Taking Two Additional Nodes without Adding

提问人:KarthikAnurag 提问时间:9/23/2022 最后编辑:KarthikAnurag 更新时间:9/24/2022 访问量:103

问:

我正在使用双向链表并使用 C 实现它们 我使用Turbo C++作为我的编译器 但是它每次都需要两个恒定的额外节点,而无需为其编写代码 在 VS Code 中运行相同的代码 但是我应该在Turbo C++中运行它 我尝试更改系统,但没有用

'''
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

struct Node
{
    struct Node *prev;
    int data;
    struct Node *next;
} *head = NULL, *temp = NULL;

void insatbeg()
{
    int item;
    struct Node *ptr = NULL;
    printf("\nEnter Item: ");
    scanf("%d", &item);
    ptr = (struct Node *)malloc(sizeof(struct Node *));
    if (ptr == NULL)
        printf("\nOverflow Occured");
    else if (head == NULL)
    {
        ptr->data = item;
        ptr->next = ptr->prev = NULL;
        head = ptr;
    }
    else
    {
        ptr->prev = NULL;
        ptr->data = item;
        ptr->next = head;
        head->prev = ptr;
        head = ptr;
    }
}

void display()
{
    if (head == NULL)
        printf("\nList is Empty");
    else
    {
        temp = head;
        while (temp != NULL)
        {
            printf("%d\t", temp->data);
            temp = temp->next;
        }
    }
}

int main()
{
    int loopvar = 1, switchvar;
    clrscr();
code:
    while (loopvar == 1)
    {
        printf("\nEnter 1 to Insert at First");
        printf("\nEnter 2 to Display");
        printf("\nEnter: ");
        scanf("%d", &switchvar);
        switch (switchvar)
        {
        case 1:
            insatbeg();
            break;
        case 2:
            display();
            break;
        default:
            printf("\nEnter Properly: ");
            goto code;
            break;
        }
        printf("\nDo You Want to Continue: ");
        scanf("%d", &loopvar);
    }
    getch();
}
'''

此外,添加的冗余节点始终是恒定的

c 数据结构 链接列表 doublebly-linked-list turbo-c ++

评论

0赞 Machavity 9/25/2022
评论不用于扩展讨论;此对话已移至 Chat

答:

2赞 Vlad from Moscow 9/23/2022 #1

此内存分配

ptr = (struct Node *)malloc(sizeof(struct Node *));

无效。您为指针类型分配了内存,而您需要为该类型的对象分配内存。所以写struct Node *struct Node

ptr = (struct Node *)malloc(sizeof(struct Node));

同样在此代码片段中

else
{
    ptr->prev = NULL;
    ptr->data = item;
    ptr->next = head;
    head = ptr;
}

忘记设置头节点的数据成员。写prev

else
{
    ptr->prev = NULL;
    ptr->data = item;
    ptr->next = head;
    head->prev = ptr;
    head = ptr;
}

请注意,该指针未在程序中使用。temp1

如果使用编译器 Turbo C++ 的代码未按预期工作,则尝试显式初始化指向头节点的指针

struct Node
{
    struct Node *prev;
    int data;
    struct Node *next;
} *head = NULL, *temp, *temp1;

评论

0赞 KarthikAnurag 9/23/2022
我试过了,但结果是一样的
0赞 Vlad from Moscow 9/23/2022
@KarthikAnurag我看不到可以在哪里添加冗余节点。
0赞 Vlad from Moscow 9/23/2022
@KarthikAnurag 请参阅我附加的答案。
0赞 KarthikAnurag 9/23/2022
我试过了,我在声明后将所有使用的指针初始化为 null。它没有帮助
0赞 Vlad from Moscow 9/23/2022
@KarthikAnurag 你是否完全按照我在回答中显示的那样做了?如果是这样,那么在这种情况下,我什么也说不出问题是什么。