C++ 双链表维护排序列表
如何在没有排序功能的情况下维护已排序的列表。添加节点时,我希望保持列表的排序。 在删除节点时也是如此C++ 双链表维护排序列表,c++,list,C++,List,如何在没有排序功能的情况下维护已排序的列表。添加节点时,我希望保持列表的排序。 在删除节点时也是如此 #include <iostream> #include <cstdlib> #include <string> using namespace std; struct Node { //node declare double value; Node *next; Node *prev; Node(doub
#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;
}
#包括
#包括
#包括
使用名称空间std;
结构体类型
{
//节点声明
双重价值;
节点*下一步;
节点*prev;
节点(双y)
{
值=y;
next=prev=NULL;
}
};
类DLinkedList
{
节点*前端;
节点*返回;
公众:
DLinkedList()
{
前=空;后=空;
}
//声明函数
void NodeFront(双x);
无效节点回退(双x);
void disproward();
void disp reverse();
};
void DLinkedList::NodeFront(双x)
{
节点*n=新节点(x);
if(front==NULL)
{
前=n;
back=n;
}
其他的
{
前->前=n;
n->next=前;
front=n;}
}
void DLinkedList::节点回退(双x)
{
节点*n=新节点(x);
if(back==NULL)
{
前=n;
back=n;
}
其他的
{
后退->下一步=n;
n->prev=返回;
back=n;
}
}
//转发节点
void DLinkedList::dispfroward()
{
节点*温度=前部;
cout-NodeFront(100.0);
list->dispfroward();
list->dispReverse();
cin.get();
返回0;
}
听起来您需要一个新功能:
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
}
保持它的分类相当容易。添加另一个方法NodeSorted(坏名字,我只是按照您的约定,它们应该是insertFront、insertBack、insertSorted)。
这个方法应该做的是——将节点插入到适当的位置,这样你们就可以浏览你们的列表,一旦找到大于你们需要插入的元素,就在它前面插入你们的节点。请注意,要使此类节点正常工作,您需要保持列表排序,即避免使用NodeFront和NodeFront。当然,如果正确实现,NodeSorted本身将保持列表处于已排序状态。如果要保持已排序的键,则链表实际上是错误的数据结构。如果要保持排序的键,就像是一个家庭作业或不了解
std::list
的人。