按排序顺序将节点插入链接列表

时间:2017-10-19 19:53:25

标签: c++ sorting pointers linked-list container-classes

我需要帮助将类节点中的数据插入到链表中。 List是节点的容器。它们需要根据姓氏,名字和年龄进行排序。 (我已经有运算符函数来比较它们)我只是不确定如何使用指针插入和排序它们。 下面是我的两个类定义,以及到目前为止我的插入函数。我还提供了一个潜在的选择排序算法,该算法来自之前的项目,可以通过加工来实现。有人可以帮忙吗?

//类声明

 class node;
    class list
    {
    public:
    void insert(string f, string l, int a);
    int length();

private:
    node *head;
    int listlength;
};
class node
{
    friend list;
public:
    node();                           // Null constructor
    ~node();                          // Destructor 
    void put(ostream &out);           // Put
    bool operator == (const node &);  // Equal
    bool operator < (const node &);   // Less than
private:
    string first, last;
    int age;
    node *next;
};  

//如何在MAIN中调用insert

while (!infile.eof())
        {
            infile >> first >> last >> age;

            // Process if okay

        if (infile.good())
            a.insert(first, last, age);
        };  

//插入函数

  void list::insert(string f, string l, int a)
        {
        node *temp1, *temp2 = head;
        temp1 = new node();
        temp1->first = f;
        temp1->last = l;
        temp1->age = a;
        temp1->next = NULL;
        if (listlength == 0)
        {
            temp1->next = head;
        }
        else
            while (temp2->next != NULL)
            {
                ;
            }

    }

//潜在排序算法

 void sort(person b[], int count)
{
    int i = 0, j = 0, indexofsmallest = i;
    person smallest = b[i];

    for (i = 0; i < count; i++)
    {
        smallest = b[i];
        indexofsmallest = i;

        for (j = i+1; j < count; j++)
        {
            if (b[j] < smallest)
            {
                smallest = b[j];
                indexofsmallest = j;
            }
        }

        //cstdlib swap function

        swap(b[i], b[indexofsmallest]);
    }

}

2 个答案:

答案 0 :(得分:2)

如果您真的想要对链表进行排序(不推荐使用),则必须调整算法以使用指针而不是数组索引。这看起来像这样:

void sort(node* head, int count)
{
    // int i = 0, j = 0,
    node* smallest = head;

    while (head != NULL)
    {
    smallest = head;
    node* toTest = head->next;
    while (toTest != NULL)
    {
        if (toTest->age < smallest->age)
        {
            smallest = toTest;
        }
        toTest = toTest->next;
    }

    //make your own swap function

    pointerSwap(head, smallest);

    head = head -> next;
}

}

您可以编写适用于指针的自己的交换算法,除非您在列表中发送项目之前跟踪该项目,否则这可能很难。

答案 1 :(得分:1)

由于无法快速访问链表中的每个元素,所有常规排序算法都会花费太多时间,特别是在单链表中,因此一种方法是在插入过程中保持列表排序。最坏情况O(n ^ 2)