c++ - 将链接列表转换为排序列表

标签 c++ list

<分区>

如何在插入新项目时将此列表转换为订单列表?我知道从哪里开始,但缺少一小块拼图。

这是我的代码:

void Node:: insert(int dat)
 {
    Node * newnode = new Node();
    newnode->data=dat;
    newnode->next=NULL;
    if(first==NULL)
    {
        first=newnode;
    }
    else
    {
        Node *temp=first;
        while(temp->next!=NULL)
        { temp=temp->next; }
        temp->next=newnode;
    }
}

最佳答案

尝试以下操作

void Node:: insert( int dat )
{
    Node *prev = NULL;
    Node *current = first;

    while ( current != NULL && !( dat < current->data ) )
    { 
        prev = current;
        current = current->next;
    }

    Node *newnode = new Node { dat, current };

    if ( prev != NULL ) prev->next = newnode;
    else first = newnode;
}

我想 Node 被定义为

struct Node
{
   int data;
   Node *next;
};

声明

Node *newnode = new Node { dat, current };

你可以代替

Node *newnode = new Node();
newnode->data = dat;
newnode->next = current;

如果 first 是它的数据成员,那么类 Node 似乎定义不正确。

这是一个演示该功能的简化示例。当然不是完整的例子

#include <iostream>

class List
{
public: 
    List() : first( NULL ) {}
    void insert( int dat )
    {
        Node *prev = NULL;
        Node *current = first;

        while ( current != NULL && !( dat < current->data ) )
        { 
            prev = current;
            current = current->next;
        }

        Node *newnode = new Node { dat, current };

        if ( prev != NULL ) prev->next = newnode;
        else first = newnode;
    }

    void display() const
    {
        for ( Node *current = first; current != NULL; current = current->next )
        {
            std::cout << current->data << ' ';
        }
    }
private:
    struct Node
    {
        int data;
        Node *next;
    } *first;
};

int main() 
{
    List l;

    l.insert( 5 );
    l.insert( 2 );
    l.insert( 7 );
    l.insert( 8 );
    l.insert( 1 );
    l.insert( 0 );
    l.insert( 4 );
    l.insert( 6 );
    l.insert( 9 );
    l.insert( 3 );

    l.display();
    std::cout << std::endl;

    return 0;
}

输出是

0 1 2 3 4 5 6 7 8 9

关于c++ - 将链接列表转换为排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26576175/

相关文章:

c++ - 遍历矩阵的方法

python - “Int”对象没有属性

java - 在 Java 8 中使用 lambda 表达式时出现错误的非法开头

python - 创建一个新列表并根据 pandas 系列的值填充它

c++ - 如何计算 OpenCV 中图像中的提示数?

c++ - mpirun : Unrecognized argument mca

c++ - subdir.mk 中的 Eclipse CDT 错误

c++ - boolean 运算符++ 和 --

java - 如何将 "add parsed string that used filter"转换为字符串 ArrayList

python - 字典列表中的问题