I have a trouble implementing doubly linked list especially in a function that swap the adjacent elements.
Here is my original code:
#include<iostream>
using namespace std;
struct node {
int data;
node *prev;
node *next;
};
node *head = NULL;
node* getNewNode (int i){
node *newNode = new node; //allocate a dynamic memory in the heap
newNode->data = i;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
void InsertAtHead(int i){
node *newNode = getNewNode(i);
if (head == NULL){ //addressing inserting the first node in the list.
head = newNode;
return;
}
newNode->next = head;
head->prev = newNode;
head = newNode;
}
void swapAdjacent() {
node *temp = head;
while (temp != NULL ) {
node *temp1 = temp;
node *temp2 = temp->next;
temp1->next = temp2->next;
temp2->prev = temp1->prev;
if (temp1->prev != NULL) {
temp1->prev->next = temp2;
}
temp1->prev = temp2;
temp2->next = temp1;
if (temp == head) {
head = temp2;
}
temp = temp->next->next;
}
}
void display (){
node *temp = head;
while (temp != NULL){
cout <<temp->data << '\t';
temp = temp->next;
}
cout << '\n';
}
int main (){
InsertAtHead(8);
InsertAtHead(4);
InsertAtHead(12);
InsertAtHead(3);
InsertAtHead(-8);
InsertAtHead(7);
cout << "The original list is: " << endl;
display();
swapAdjacent();
cout << "The list after swapping the adjacent elements is: " << endl;
display();
return 0;
}
The original list is The original list is: 7 -8 3 12 4 8 The output I got after calling swapAdjacent() is : -8 7 3 4 12 8 while I am looking for: -8 7 12 3 8 4
I tried visualizing this with pen and paper, did several attempts to look it up and even I used chat GPT to no avail. I always don't get the output I am looking for.
I appreciate all of your feedback.
Aucun commentaire:
Enregistrer un commentaire