-
Notifications
You must be signed in to change notification settings - Fork 0
/
2023283_Lab6_keshav.cpp
88 lines (74 loc) · 1.73 KB
/
2023283_Lab6_keshav.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
82
83
84
85
86
87
88
#include <iostream>
#include <vector>
using namespace std;
class Node {
public:
int value;
Node* next;
Node(int value) : value(value), next(nullptr) {}
};
class LinkedList {
public:
Node* head;
LinkedList() : head(nullptr) {}
void add(int value) {
Node* newNode = new Node(value);
if (!head) {
head = newNode;
} else {
Node* current = head;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
}
void rightrotate(int k) {
if (!head || !head->next || k == 0) {
return;
}
int length = 1;
Node* tail = head;
while (tail->next) {
tail = tail->next;
length++;
}
k %= length;
if (k == 0) {
return;
}
int tailpositionnew = length - k;
Node* newTail = head;
for (int i = 0; i < tailpositionnew - 1; i++) {
newTail = newTail->next;
}
tail->next = head;
head = newTail->next;
newTail->next = nullptr;
}
void display() {
Node* current = head;
while (current) {
cout << current->value;
if (current->next) {
cout << " -> ";
}
current = current->next;
}
cout <<endl;
}
};
int main() {
LinkedList ll;
vector<int> input = {1, 2, 3, 4, 5};
int k = 2;
for (int val : input) {
ll.add(val);
}
cout << "Original linked list:" << endl;
ll.display();
ll.rightrotate(k);
cout << "after rotating to the right by " << k << " places:" << endl;
ll.display();
return 0;
}