问题出现在我写的插入函数中。插入链接列表问题
3个条件必须工作,我测试了b/w 1和2,b/w 2和3,并且作为最后一个元素,他们的工作。
编辑; 这是我自己的问题。我没有意识到我把MAXINPUT = 3(而不是4)。我感谢所有帮助我成为一个更好的程序员,采用更先进和C++的更简洁特点的努力。
基本上,问题已经解决了。
效率不是我关心的(尚未)。请指导我完成这个调试过程。
非常感谢。
#include<iostream>
#include<string>
using namespace std;
struct List // we create a structure called List
{
string name;
string tele;
List *nextAddr;
};
void populate(List *);
void display(List *);
void insert(List *);
int main()
{
const int MAXINPUT = 3;
char ans;
List * data, * current, * point; // create two pointers
data = new List;
current = data;
for (int i = 0; i < (MAXINPUT - 1); i++)
{
populate(current);
current->nextAddr = new List;
current = current->nextAddr;
}
// last record we want to do it sepeartely
populate(current);
current->nextAddr = NULL;
cout << "The current list consists of the following data records: " << endl;
display(data);
// now ask whether user wants to insert new record or not
cout << "Do you want to add a new record (Y/N)?";
cin >> ans;
if (ans == 'Y' || ans == 'y')
{
/*
To insert b/w first and second, use point as parameter
between second and third uses point->nextAddr
between third and fourth uses point->nextAddr->nextAddr
and insert as last element, uses current instead
*/
point = data;
insert(());
display(data);
}
return 0;
}
void populate(List *data)
{
cout << "Enter a name: ";
cin >> data->name;
cout << "Enter a phone number: ";
cin >> data->tele;
return;
}
void display(List *content)
{
while (content != NULL)
{
cout << content->name << " " << content->tele;
content = content->nextAddr;
cout << endl; // we skip to next line
}
return;
}
void insert(List *last)
{
List * temp = last->nextAddr; //save the next address to temp
last->nextAddr = new List; // now modify the address pointed to new allocation
last = last->nextAddr;
populate(last);
last->nextAddr = temp; // now link all three together, eg 1-NEW-2
return;
}
打扰愚蠢的问题:你是什么意思的黑白?什么插入(());意思?关于 – Simon 2010-05-10 16:27:44
b/w意味着插入(())mwans将上述任何参数。例如,插入((point-> nextAddr))。 – CppLearner 2010-05-10 16:40:10