1

我正在尝试将一个元素添加到链表的后面。

我能够添加元素,并且在第一次尝试时一切正常,但是当我尝试添加另一个元素时,之前添加的元素变成了垃圾值。

当我用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;
}
4

1 回答 1

2

正如 WhozCraig 已经提到的,您需要将以下行添加到构造函数中

Head = NULL;

然后您可以将类似这样的内容添加到函数 Addelementfromback 的开头

If(Head == NULL)
{
     Head = new Node;
     Head->data = horoscope;
     Head->next = NULL;
     return;
}

您还需要更改 LinkedList::process_example 中的以下行

 char elements[30];

 char* elements = new char[30];
于 2013-02-02T15:32:39.190 回答