Reputation: 35
template <class T>
class Node
{
public:
T data;
Node<T>* prev;
Node<T>* next;
// default constructor (parameterized)
template <class T>
Node(T value)
{
data = value;
prev = NULL;
next = NULL;
}
};
template <class T>
T CircularLinkedList<T>::RemoveAt(int p){
Node<T>* temp = head;
if (head == NULL){
return 0;
}
else if (p == 0){
return temp;
}
else{
temp = head->next;
for (int i = 0; i < p-1; i++)
temp = temp->next;
temp->next =
}
}
I'm making remove function of doubly linked list.
I don't know how to proceed this code if p is greater than equal to 0.
How to remove value and return it at the same time?
Upvotes: 2
Views: 371
Reputation: 5593
Assuming head is at position p == 0, then you should first check that head is not the last element since the list will be empty if it is. Then you simply iterate over the list until the desired position and set temp's prev->next to temp->next and similarly temp's next->prev to temp->prev to remove temp. This works for both values of 0 and greater than 0.
Here's a quick example of a possible implementation:
template <class T>
T CircularLinkedList<T>::RemoveAt(int p)
{
Node<T>* temp = head;
if(head == NULL)
{
return NULL;
}
if(head->next == head)
{
// Set head to null and return
head = NULL;
return NULL;
}
// List won't be depleted after removal
// Move to next p number of times, temp already at head
for(int i = p; i > 0; --i)
{
temp = temp->next;
}
// Now remove temp and let it be return value
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
return temp.data;
}
Upvotes: 1