Reputation: 848
I'm writing a circular list class for my college assignment and I need to implement a function that removes the node at the given index from the circular linked list and returns a pointer to that node.
Here is my node class. All functions work fine.
struct Node
{
int nData;
Node* next;
Node(); // Null Constructor
Node(int data); // Parameterized Constructor
Node(Node& newNode); // Copy constructor
~Node(); // Destructor
Node& Print(); // display function
};
And here is my node remove function.
Node* CCircleList::removeAt(int index) // remove node at specified index
{
if (index < 0)
{
index = 0;
}
if (index == 0)
{
return remove();
}
else if (index >= count)
{
demoteIndex(); // tail points to it's predecessor
Node* ptr = tail->next;
tail->next = ptr->next;
ptr->next = NULL;
setPosition(0);
return ptr;
}
else if (index = (count - 1))
{
promoteIndex(); // tail points to tail->next
setPosition(index - 1); // sets Node pointer current to index
Node* ptr = current->next;
promoteIndex();
current->next = ptr->next;
ptr->next = NULL;
return ptr;
}
else
{
setPosition(index - 1);
Node* ptr = current->next;
current->next = ptr->next;
ptr->next = NULL;
return ptr;
}
}
count = number of nodes in list.
tail = last node in list.
tail->next = first node in the list.
The function works for all indices except for count-1, Any help would be appreciated. Thanks in advance.
Code of other functions
CCircleList& CCircleList::promoteIndex() // tail points to it's successor
{
if (!tail) return *this;
tail = tail->next;
return *this;
}
CCircleList& CCircleList::demoteIndex() // tail points to it's predecessor
{
if (!tail) return *this;
for (int i = 1; i <= count - 1; i++)
{
tail = tail->next;
}
return *this;
}
CCircleList& CCircleList::setPosition(int index) // set current to specified index
{
if (index < 0) index = 0;
if (index >= count) index = count - 1;
current = tail->next;
for (int i = 0; i < index; ++i)
{
current = current->next;
}
return *this;
}
Upvotes: 0
Views: 356
Reputation: 45414
Instead of
else if (index = (count - 1))
try
else if (index == (count - 1))
Upvotes: 1