如何在没有排序功能的情况下维护排序的列表。当我添加节点时,我想保持列表排序。删除节点时也是如此。
#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;
}