Swap nodes of doubly linked list without swapping data

The question asks to swap extreme nodes (head and tail) of the doubly linked list without swapping in other words, Swap nodes of doubly linked list without swapping data or Nodes in Pairs in C++

Swap Nodes in Pairs in C++

Abstract class in CPP (ReadHere)

#include <iostream>
#include <stdlib.h>
using namespace std;

struct Node {
int value;
struct Node * next;
struct Node * prev;
};
void insert(int val);
void print();
void swapExtremeDNodes();
struct Node * start = NULL, *curr = NULL;
int main() {
/* code */
print();
insert(10);
insert(20);
insert(30);
insert(40);
insert(50);
print();


swapExtremeDNodes();

print();

//system("pause");
return 0;
}

void insert(int val) {
struct Node * ptr;
ptr = new Node();
ptr -> next = NULL;
ptr -> prev = NULL;
ptr -> value = val;

if (start == NULL && curr==NULL) {
start = ptr;
curr = start;
return;
} 

while (curr->next!= NULL) {
curr = curr -> next;
}
curr -> next = ptr; 
ptr -> prev = curr;

curr=curr->next;

}
void swapExtremeDNodes() {

Node *tempTail;

cout<<"current value"<<curr->value<<endl;
cout<<"start value"<<start->value<<endl;

tempTail=curr;
curr=start;
start=tempTail;
}

void print() {
if (start == NULL) {
cout << "List is Empty" << endl;
} else {
struct Node * cur = start;
while (cur != NULL) {
cout << cur -> value << endl;
cur = cur -> next;
}
}
}

Swapping nodes in doubly linked list

Output

List is Empty

10

20

30

40

50

Current Value 50

Start Value 10

50

Inheritance program in C++ (ReadHere)

What is the template in C++ (ReadHere)

Linked list Program in Cpp

Swap node of doubly linked list without swapping data
Swap node of doubly linked list without swapping data

How to swap nodes in Cpp Program

Hello Dear, today we learn about the doubly linked list program in Cpp help of Program.
Please don’t forget to give your valuable feedback. Maybe in some cases program will not give you Valuable Output, so don’t worry about it. Always try to Understand and Code Yourself Thanks.

END

Leave a Reply

x