c++ - 单向链表的头部一直指向列表中的最后一项

标签 c++

<分区>

我正在尝试在 C++ 上创建单向链表。我正在使用 3 个函数执行此操作,这些函数基于结构“DiseaseList”创建一个项目,将该项目添加到列表中,然后将其打印出来。

我已经整理这段代码几个小时了,我似乎无法阻止它把这个列表的头部定位到最后一个项目。只有 2 点可以改变头部(其中 head = *),但这一定是对我所写内容的误解,因为我无法弄清楚。

例如,我添加了两个新元素“1”和“2”。它将永远循环输出“2”。请结束我的痛苦:(

#include <iostream>
using namespace std;

typedef struct DiseaseList
{
    int a;
    struct DiseaseList *Next;

}DList; //Not sure if I needed DList here or should have just used DiseaseList

DList* CreateElement();
void printList(DList*);
DList* AddElement(DList*, DList*);



int main(void)
{
int choose;
DList *Head = NULL, *NewElement;
do {

cout << "1. Add element" << endl;
cout << "2. Print list" << endl;
cout << "3. Exit" << endl;
cin >> choose;
switch (choose)
{
    case 1: 
        NewElement = CreateElement();
        Head = AddElement(Head, NewElement); 
        break;
    case 2: printList(Head); break;
    case 3: return 0;
}
} while (1);

}

DList* CreateElement() //Creates a new item for the list
{
    DList* temp;

    cout << "New Number:";
    cin >> temp->a;
    temp->Next = NULL;
    return temp;
}

DList* AddElement(DList *Head, DList *NewElement) //Adds new item from CreateElement to the list
{

if (Head == NULL)
{
    NewElement->Next = NULL;
    Head = NewElement;

}
else{

DList *temp = Head;
while (temp->Next != NULL)
{
    temp = temp->Next;
}
    temp->Next = NewElement;

}
return Head;
}

void printList(DList* Head)
{
    while (Head != NULL)
{
    cout << Head->a << endl;
    Head = Head->Next;
}

}

最佳答案

CreateElement 实际上并没有创建元素!

这意味着它正在返回(并使用)一个未初始化的指针,我很惊讶你的编译器没有显示警告。

替换这一行:

DList* temp;

DList* temp = new Dlist;

关于c++ - 单向链表的头部一直指向列表中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27282694/

相关文章:

c++ - qt中的占位符

c++ - 多重定义 - 为什么我不能在标题中定义它们

c++ - CPP预处理器到C预处理器的转换问题

c++ - Xcode 配置文件不适用于汇编代码

c++ - 根据支持的指令选择要使用的程序集实现

c++ - 如何在 C++ 中使用 for 循环初始化字符串 vector 的 vector ?

c++如何使用引用计数管理对象缓存

c++ - 在 Windows XP 上替换::SHCreateItemFromParsingName()

c++ - 分组#defines 的最佳方式

c++ - 使用 lambda 函数定义运算符