-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListSwap.cpp
More file actions
88 lines (78 loc) · 2.08 KB
/
Copy pathLinkedListSwap.cpp
File metadata and controls
88 lines (78 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
using namespace std;
struct LLnode {
int data;
LLnode *next;
};
//Traversal
void display(LLnode *ptr) {
while(ptr != NULL) {
cout << "Element: " << ptr->data <<"->";
ptr = ptr->next;
}
}
// Function to swap two nodes in a linked list
LLnode *swapNodes(LLnode *head, int value1, int value2) {
if(value1 == value2) {
cout<<"Same values,no swaping required."<<endl;
return head;
}
LLnode *prev1 = NULL, *curr1 = head;
while(curr1 != NULL && curr1->data != value1) {
prev1 = curr1;
curr1 = curr1->next;
}
LLnode *prev2 = NULL, *curr2 = head;
while (curr2 != NULL && curr2->data != value2) {
prev2 = curr2;
curr2 = curr2->next;
}
// If either of the values is not found
if(curr1 == NULL || curr2 == NULL) {
cout << "Node not found!" << endl;
return head;
}
// If curr1 is not the head of the list
if(prev1 != NULL) {
prev1->next = curr2;
} else{
head = curr2;
}
// If curr2 is not the head of the list
if(prev2 != NULL) {
prev2->next = curr1;
} else {
head = curr1;
}
// Swap next pointers
LLnode *temp = curr1->next;
curr1->next = curr2->next;
curr2->next = temp;
return head;
}
int main() {
LLnode *head, *second, *third, *fourth, *fifth;
// Allocate memory for nodes in linked list
head = (struct LLnode *)malloc(sizeof(LLnode));
second = (struct LLnode *)malloc(sizeof(LLnode));
third = (struct LLnode *)malloc(sizeof(LLnode));
fourth = (struct LLnode *)malloc(sizeof(LLnode));
fifth = (struct LLnode *)malloc(sizeof(LLnode));
// Initialize data
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = fourth;
fourth->data = 4;
fourth->next = fifth;
fifth->data = 5;
fifth->next = NULL;
cout<<"Before swapping:" << endl;
display(head);
head = swapNodes(head, 1, 2);
cout<<"\nAfter swapping:" << endl;
display(head);
return 0;
}