【发布时间】:2013-02-02 11:37:44
【问题描述】:
我正在尝试将一个元素添加到链表的后面。
我能够添加元素,并且在第一次尝试时一切正常,但是当我尝试添加另一个元素时,之前添加的元素变成了垃圾值。
当我用函数声明中完全相同的代码替换主菜单中的LinkedList::process_example(int choice,LinkedList &set) 函数时,问题就解决了。谁能给我解释一下为什么????
#include <iostream>
#include <ctime>
using namespace std;
struct Node;
typedef void* VoidPtr;
typedef Node* NodePtr;
typedef char* ZodiacSign;
const int MAX=12;
struct Node
{
NodePtr next;
VoidPtr data;
};
class LinkedList
{
public:
LinkedList();
//~LinkedList();
void Addelement(VoidPtr);
void printSet();
int compareEqual(VoidPtr,VoidPtr);
void swap(int num,int x,ZodiacSign tempSign [MAX]);
void process_example(int choice);
int check_cardinality();
void Addelementfromback(VoidPtr);
private:
NodePtr head;
ZodiacSign getVP(VoidPtr);
};
int choice=1;
LinkedList set;
do {
cout<<endl
<<endl;
cout<<"Wish to try the following operation?"
<<endl
<<"1. Add an element to set"// the function to add to back of linked list
<<endl
<<"2. Check an element in set"
<<endl
<<"3. check carinality"
<<endl
<<"9. Quit"
<<endl
<<endl;
cout<<"Your choice : ";
cin>>choice;
cin.clear();
cin.ignore(200,'\n');
set.process_example(choice);
} while (choice !=9);
void LinkedList::process_example(int choice)
{
switch (choice)
{
case 1:
cout<<endl
<<endl
<<"Current S = ";
this->printSet();
cout<<"Enter an element :";
char element [30];
cin>>element;
cin.clear();
cin.ignore(200,'\n');
this->Addelementfromback(element);
cout<<endl
<<endl
<<"Current S = ";
this->printSet();
break;
case 3:
cout<<endl
<<endl;
cout<<"Current Set S = ";
set.printSet();
cout<<endl
<<"S has ";
int count=this->check_cardinality();
cout<<count
<<" elements";
}
}
void LinkedList::printSet()
{
NodePtr temp = head;
cout<<"{ ";
while (temp != NULL)
{
cout << getVP (temp -> data) << " , ";
temp = temp -> next;
}
cout<<" } ";
cout << endl;
}
void LinkedList::Addelementfromback(VoidPtr horoscope)
{
NodePtr temp = head;
while (temp->next != NULL)
{
temp=temp->next;
}
NodePtr element = new Node;
element->data=horoscope;
element->next=NULL;
temp->next=element;
}
【问题讨论】:
-
也许这个问题对你有帮助。 stackoverflow.com/questions/4005284/…
-
查看
LinkedList的定义可能会有所帮助;不仅仅是几个成员函数。但是在顶部,您认为:NodePtr temp = head; while (temp->next != NULL)... temp->next = element;在head为 NULL 时会做什么?换句话说,该代码的行为如何,当新元素是 first 元素时,它会将新元素指针写入哪里? -
这可能是因为在调用
process_example时,您传递了 set.process_example(choice, set) 之类的值,但在方法process_example中,您获得了set对象的地址,原因是“&”(地址)运算符?另外,我不明白使用set.process_example调用方法/函数process_example然后将set变量作为其参数之一再次传递给它的逻辑。您始终可以使用this运算符在方法process_example中访问set变量。 -
我添加了LinkedList的定义
标签: c++ debugging class linked-list