-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathreverseLLPairs.cpp
More file actions
124 lines (96 loc) · 1.74 KB
/
reverseLLPairs.cpp
File metadata and controls
124 lines (96 loc) · 1.74 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
Program : Reverse the Linked List in Pairs. (Q3: Assignment 1)
Author : © Vipin Kumar
Created on : March 20, 2018 11:38 IST
*/
#include <iostream>
#include <conio.h>
#include <cstdlib>
using namespace std;
struct node {
int data;
node* next;
};
class SinglyLinkedList {
public:
node * head;
int data;
int size;
SinglyLinkedList ();
~SinglyLinkedList ();
void insertion (int);
void swapPairs (node*);
void display ();
};
SinglyLinkedList::SinglyLinkedList () {
head = NULL;
size = 0;
}
SinglyLinkedList::~SinglyLinkedList () {
node* temp;
while (head->next != NULL) {
temp = head;
head = head->next;
delete temp;
}
}
void SinglyLinkedList::insertion (int value) {
node* newNode = new node;
newNode->data = value;
newNode->next = NULL;
node* temp;
if (head == NULL) {
head = newNode;
}
else {
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
size++;
}
void swapData (int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void SinglyLinkedList:: swapPairs (node* head) {
if (head != NULL && head->next != NULL) {
swapData (&head->data, &head->next->data);
swapPairs (head->next->next);
}
}
void SinglyLinkedList::display () {
node* temp = head;
if (head == NULL) {
cout << "Linked List is EMPTY.\n";
}
else if (head->next == NULL) {
cout << head->data;
}
else {
while (temp->next != NULL) {
cout << temp->data << "->";
temp = temp->next;
}
cout << temp->data;
}
}
int main () {
SinglyLinkedList sll;
sll.insertion (1);
sll.insertion (2);
sll.insertion (3);
sll.insertion (4);
sll.insertion (5);
sll.insertion (6);
sll.display ();
cout << '\n';
sll.swapPairs (sll.head);
sll.display ();
getch ();
return 0;
}