I'm working on a school project right now. It's an ordered(ascending) doubly linked list. I just wrote the Insert operation on it but I feel like the way I wrote it isn't that great.
void OrdListClass::Insert(ItemType item)
{
if(Find(item))
{
//throw DuplicateKeyException;
}//End Duplicate Key Check
else
{
//Due to Find, currPos points to the node that we're inserting AFTER
node* newNode = new node;
newNode->data = item;
if(currPos == nullptr)
{
//We're inserting at the head.
newNode->prev = nullptr;
newNode->next = head;
head->prev = newNode;
head = newNode;
}
else if(currPos->next == nullptr)
{
//We're inserting at the tail
newNode->next = nullptr;
newNode->prev = tail;
tail->next = newNode;
tail = newNode;
}
else
{
//We're inserting in the middle of the list.
newNode->prev = currPos;
newNode->next = currPos->next;
currPos->next->prev = newNode;
currPos->next = newNode;
}
currPos = newNode;
}//End Not Duplicate Else
}//End Insert
EDIT: Of note.. ItemType is just a typedef for an int.
bool OrdListClass::Find(/*IN*/ItemType searchKey)
{
//Skip operations if empty.
if(IsEmpty()) return false;
currPos = head;
while(!EndOfList())
{
if(currPos->data == searchKey)
{
return true;
}
else if (currPos->data > searchKey)
{
currPos = currPos->prev;
return false;
}
//else continue;
}
}
Find
function? Is it used elsewhere in the class? Is it public? \$\endgroup\$Find
implictly update somecurrPos
member and haveInsert
depend on this behavior. It'd be much better to have the lookup function return a node more explicitly, through a return value or out parameter. \$\endgroup\$