如何在没有排序功能的情况下对列表进行排序。当我添加节点时,我想维护列表排序。 删除节点时也是如此。
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
struct Node
{
//node declare
double value;
Node *next;
Node *prev;
Node(double y)
{
value = y;
next = prev = NULL;
}
};
class DLinkedList
{
Node *front;
Node *back;
public:
DLinkedList()
{
front = NULL; back = NULL;
}
//declare function
void NodeFront(double x);
void NodeBack(double x);
void dispForward();
void dispReverse();
};
void DLinkedList::NodeFront(double x)
{
Node *n = new Node(x);
if( front == NULL)
{
front = n;
back = n;
}
else
{
front->prev = n;
n->next = front;
front = n;}
}
void DLinkedList::NodeBack(double x)
{
Node *n = new Node(x);
if( back == NULL)
{
front = n;
back = n;
}
else
{
back->next = n;
n->prev = back;
back = n;
}
}
//forward nodes
void DLinkedList::dispForward()
{
Node *temp = front;
cout << "forward order:" << endl;
while(temp != NULL)
{
cout << temp->value << " " ;
cout<<endl;
temp = temp->next;
}
}
//reverse list
void DLinkedList::dispReverse()
{
Node *temp = back;
cout << "reverse order :" << endl;
while(temp != NULL)
{
cout << temp->value << " " ;
cout<<endl;
temp = temp->prev;
}
}
int main()
{
DLinkedList *list = new DLinkedList();
//front of the list
list->NodeFront(45.0);
list->NodeFront(49.0);
list->NodeFront(42.0);
list->NodeFront(48.0);
list->NodeFront(48.0);
list->NodeFront(52.0);
list->NodeFront(12.0);
list->NodeFront(100.0);
list->dispForward();
list->dispReverse();
cin.get();
return 0;
}
答案 0 :(得分:2)
听起来你想要一个新功能:
void DLinkedList::NodeSorted(double x)
{
Node *n = new Node(x);
// Step 1: Find the first node "x" that should be AFTER n.
// Step 2: Make the node before "x" link to n
// Step 2: Make "x" link to n
}
答案 1 :(得分:0)
保持它排序非常简单。添加另一个方法NodeSorted(坏名称,我只是遵循你的约定,它们应该是insertFront,insertBack,insertSorted代替)。 这个方法应该做什么 - 将节点插入到正确的位置,这样你就可以查看列表,只要找到大于你需要插入的元素,就可以在它之前插入节点。请注意,此类NodeSorted正常工作,您需要维护已排序的列表,即避免使用NodeFront和NodeFront。当然,NodeSorted本身如果正确实现将保持列表处于排序状态。