我试图在C ++上创建一个单链表。我这样做有3个函数,它们根据结构“DiseaseList”创建一个项目,将该项目添加到列表中,然后将其打印出来。
我一直在梳理这段代码几个小时,我似乎无法阻止它将此列表的头部定位到最后一项。只有2个点可以改变头部(头部= *),但它只是对我正在写的东西的误解,我无法弄明白。
比如说我添加了两个新元素,“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;
}
}
答案 0 :(得分:2)
CreateElement
实际上并没有创建元素!
这意味着它正在返回(并使用)一个未初始化的指针,我很惊讶你的编译器没有显示警告。
替换此行:
DList* temp;
与
DList* temp = new Dlist;
答案 1 :(得分:2)
除了@ TheDark的答案之外,您应该注意Head
参数永远不会在main()
中更改,除非您指定AddElement()
的返回值,因为您已经[&1;}按值重新传递指针:
DList* AddElement(DList *Head, DList *NewElement) {
最好通过引用传递Head
指针以使其正确初始化
void AddElement(DList*& Head, DList *NewElement) {
// ^ Note the &
// ...
}
答案 2 :(得分:0)
只需要小修复(也清理空白区域):
#include <iostream>
using namespace std;
typedef struct DList_
{
int a;
struct DList_ *Next;
}DList;
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);
return 0;
}
DList* CreateElement() //Creates a new item for the list
{
DList* temp = new DList;
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)
return NewElement;
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;
}
}