Description
Write a code oriented pseudocode or a C++ function that swaps two consecutive nodes in a doubly–linked list by updating their pointers (the data field inside the linked list node is not to be accessed). It returns true if possible, false otherwise. Assume the list has two sentinel nodes and n > 0. For instance, if n = 3 and list has the following data: SENTF 20 90 70 80 10 SENTRafter the call (70 and 80 are swapped)list is: SENTF 20 90 80 70 10 SENTR
struct Node
{
Node *back;
Data data;
Node *forw;
};
class DList
{
private:
Node *head;
int length;
Node *tail;
public:
bool swap(int n);
//node number n with node number n+1
};
This is my answer:
bool DList::swap(int n) {
Node *temp = head;
int count = 0;
while (temp->forw != NULL) {
if (count == n) {
Node *temp1 = new Node;
Node *temp2 = new Node;
temp2 = temp->back->back;
Node *temp3 = new Node;
temp3=temp->forw;
temp1 = temp;
temp1->forw = temp->back;
temp1->back = temp->back->back;
temp = temp1->forw;
temp->back = temp1;
temp->forw = temp3;
temp2->forw = temp1;//80
return true;
}
else {
temp = temp->forw;
count++;
}
}
return false;
}
The next question is What happens if the list has only one number or n > length?