【问题标题】:Circular doubly linked list - adding node at beginning but getting no output, Please check what we are missing, Thanks循环双向链表 - 在开头添加节点但没有输出,请检查我们缺少什么,谢谢
【发布时间】:2022-06-15 21:58:26
【问题描述】:

看似简单的代码,但没有给出任何输出,我已经尝试按照我的理解干运行它,但仍然无法调试,请检查一下。谢谢!

#include <stdio.h>
#include <stdlib.h>
struct node {
    struct node* prev;
    int data;
    struct node* next;
};
struct node* addtoEmpty(int data)
{
    struct node* temp = (struct node*)malloc((sizeof(struct node)));
    temp->data = data;
    temp->prev = NULL;
    temp->next = NULL;
    return temp;
}
struct node* addatBeg(struct node* tail, int data)
{
    struct node* newp = addtoEmpty(data);
    if (tail == NULL) {
        return newp;
    }
    else {
        struct node* temp = tail->next;
        newp->next = temp;
        newp->prev = tail;
        temp->prev = newp;
        tail->next = newp;
        return tail;
    }
}
void printlist(struct node* tail)
{
    if (tail == NULL) {
        printf("No element in the list");
    }
    else {
        struct node* temp = tail->next;
        do {
            printf("%d ", temp->data);
            temp = temp->next;
        } while (temp != tail->next);
    }
    printf("\n");
}
int main()
{
    struct node* tail = NULL;
    tail = addtoEmpty(45);
    tail = addatBeg(tail, 67);
    printlist(tail);
    return 0;
}

【问题讨论】:

  • 我删除了 C++ 标签,因为这是纯 C 代码。如果您实际使用的是 C++,请移除 C 标签并添加 C++ 标签。
  • 这不是一个循环列表。这一行:temp-&gt;prev = newp; 崩溃,因为 temp 为空。调试器可能会告诉你。

标签: c doubly-linked-list


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 2014-07-13
  • 2021-06-01
相关资源
最近更新 更多