我已经实现了一个创建已排序的双向链表的程序。一切都运行良好,除了我似乎无法弄清楚程序在哪里接受节点66作为头,而44(更小)作为节点之后。这是我的添加功能。
bool SortedDoublyLinkedList<ItemType>::add(const ItemType &newEntry) {
Node<ItemType> *newNode = new Node<ItemType>();
newNode->setItem(newEntry);
if (size == 0) //checks if linked list is empty -> add elements if so.
{
head = newNode;
newNode->setNext(NULL);
newNode->setPrev(NULL);
tail = newNode;
}
// checks if the new node to be added is small than node that head is currently pointing to. If so, add new node before head and make it the new head of list.
else if (newNode->getItem() < head->getItem()) {
head->setPrev(newNode);
newNode->setNext(head);
newNode->setPrev(NULL);
head = newNode;
}
// checks if new node is bigger than the tail node (or last node). If so, add new node to end of list. Then make that new node the tail (end) of list.
else if (newNode->getItem() > tail->getItem()) {
tail->setNext(newNode);
newNode->setNext(NULL);
newNode->setPrev(tail);
tail = newNode;
}
// if the new node is neither of the mentioned situations, add the new node in the correct position in middle of the list. TempPtr1 acts as a ptr and the new node will be added directly in front of it.
else {
Node<ItemType> *tempPtr1;
tempPtr1 = head;
while (newNode->getItem() > tempPtr1->getItem()) {
tempPtr1 = tempPtr1->getNext();
}
newNode->setPrev(tempPtr1->getPrev());
newNode->setNext(tempPtr1); // = tempPtr1;
tempPtr1->getPrev()->setNext(newNode);
tempPtr1->setPrev(newNode);
}
size++;
return true;
}
输出: 66 44 88 88