我在我的列表中插入节点时遇到问题,以便它们按顺序显示。这是我将节点插入列表的函数:
void LinkedList::insert(const int item)
{
Node *newNode = new Node;
newNode -> data = item;
if(head == NULL)
{//in case of empty list
head = tail = newNode;
newNode -> next = NULL;
newNode -> previous = NULL;
++count;
} else {
Node *ptr = head;
while((ptr && (ptr -> next) != NULL) && (item < (ptr -> data)))
{//traversing the list to find the correct insertion point
ptr = ptr -> next;
}
if((ptr -> previous) == NULL)
{//the insertion point is before the head of the list
newNode -> previous = NULL;
newNode -> next = ptr;
ptr -> previous = newNode;
head = newNode;
++count;
}
else if((ptr -> next) == NULL)
{//end of list insertion
newNode -> next = NULL;
newNode -> previous = ptr;
ptr -> next = newNode;
tail = newNode;
++count;
} else {//middle of the list insertion
(ptr -> previous) -> next = newNode;
newNode -> previous = ptr -> previous;
newNode -> next = ptr;
ptr -> previous = newNode;
++count;
}
}
}
唯一有序的节点是插入到列表头部或尾部的节点。当必须将节点插入到列表的中间时,节点的顺序就会被违反。这是我从 main() 打印结果时得到的结果
int main()
{
LinkedList database;
cout<<"The count is: "<< database.lenght() << endl;
database.insert(11);
database.insert(1);
database.insert(8);
database.insert(62);
database.insert(55);
database.insert(100);
database.insert(00);
cout<< endl;
cout<<"The count is: "<< database.lenght() << endl;
cout<< endl;
database.print_forwards();
return 0;
}
输出:
The count is : 0
the count is : 7
100
62
55
8
1
11
0
有人可以解释一下我的插入功能有什么问题吗?谢谢,