問題出現在我寫的插入函數中。插入鏈接列表問題
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