在双向链表中排序对象

时间:2017-11-25 04:08:22

标签: c++ list data-structures linked-list

我正在尝试对包含一组对象的名称和id属性的双向链表进行排序,我想用id对其进行排序 我有两个类用于Employee,另一个用于LinkedList 这是来自LinkedList类的函数sort和function swap 问题是这种排序功能没有排序,它在排序后显示无意义的数据

void LinkedList::Sort()
{
    Employee *tempFirst,*tempSeconed;
    tempFirst=pStart;
    tempSeconed = pStart->pNext;

    while(tempSeconed!=NULL && tempFirst->getId()<tempSeconed->getId())
    {
        tempFirst= tempFirst->pNext;
        tempSeconed= tempSeconed->pNext;

    }

    swap(tempFirst,tempSeconed);

}
void LinkedList::swap(Employee *x , Employee *y)
{
    Employee *temp;
    temp->setName(x->getName());
    temp->setId(x->getId());

    x->setName(y->getName());
    x->setId(y->getId());

    y->setName(temp->getName());
    y->setId(temp->getId());
}

这是班级员工

class Employee
{
    private:
        int id;
        char* name;


    public:
        Employee *pNext;
        Employee *pPrevious;
        void printEmployee();

        void setId(int id);
        int getId();

        void setName(char* name);
        char* getName();

        Employee()
        {
            name = new char[50];
            id=0;
            strcpy(this->name , "no name");
            pNext = NULL;
            pPrevious =NULL;
        }
        Employee(int id , char* name)
        {
            this->id = id;
            strcpy(this->name , name);
        }

        Employee(Employee &z)
        {
            this->id = z.id;
            strcpy(this->name , z.name);
            //this->name = z.name;
        }
        void operator =(Employee &z)
        {

            this->id = z.id;
            this->name=z.name;
        }
        void operator = (Employee e);


};

这是类LinkedList

class LinkedList
{
    protected:
        Employee *pStart;
        Employee *pEnd;

    public:
        LinkedList()
        {
            pStart = pEnd = NULL;
            cout<<"constructor is called"<<endl;
        }
        ~LinkedList()
        {
            // freeList();
        }
        void addList(Employee *pltem);
        void insertList(Employee *pltem);
        Employee* searchList(int id);
        int DeleteList(int id);
        void freeList();
        void displayAll();




        //void print();
        int getCounter();
        void insert();
        void Sort();
        void swap(Employee *x , Employee *y);
};

0 个答案:

没有答案