-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathsol.cpp
81 lines (70 loc) · 1.65 KB
/
sol.cpp
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
#include <iostream>
struct Node{
int data;
Node *next;
};
Node *createNode(int data){
Node *temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
void printLinkedList(Node *head){
while (head->next!=NULL){
std::cout<<head->data<<" --> ";
head = head->next;
}
std::cout<<head->data<<std::endl;
}
Node *swapEveryTwo(Node *head){
Node *curr = head;
while (curr->next!=NULL && curr->next->next!=NULL) {
int cache = curr->data;
curr->data = curr->next->data;
curr->next->data = cache;
curr = curr->next->next;
}
return head;
}
void test(){
std::cout<<"\nTest Case 1\n";
Node *head = createNode(1);
Node *curr = head;
for (int i=2; i<=4; i++){
curr->next = createNode(i);
curr = curr->next;
}
std::cout<<"Original Linked List"<<std::endl;
printLinkedList(head);
Node *swapped = swapEveryTwo(head);
std::cout<<"Modified Linked List"<<std::endl;
printLinkedList(swapped);
std::cout<<"\nTest Case 2\n";
head = createNode(1);
curr = head;
for (int i=2; i<=3; i++){
curr->next = createNode(i);
curr = curr->next;
}
std::cout<<"Original Linked List"<<std::endl;
printLinkedList(head);
swapped = swapEveryTwo(head);
std::cout<<"Modified Linked List"<<std::endl;
printLinkedList(swapped);
std::cout<<"\nTest Case 3\n";
head = createNode(1);
curr = head;
for (int i=2; i<=10; i++){
curr->next = createNode(i);
curr = curr->next;
}
std::cout<<"Original Linked List"<<std::endl;
printLinkedList(head);
swapped = swapEveryTwo(head);
std::cout<<"Modified Linked List"<<std::endl;
printLinkedList(swapped);
}
int main(){
test();
return 0;
}