-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDoublyLinkedList_MovingHeadPosition.cpp
112 lines (96 loc) · 2.41 KB
/
DoublyLinkedList_MovingHeadPosition.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <iostream>
using namespace std;
// Definition of Node structure
struct Node {
int data;
Node* next;
Node* prev;
Node(int val) {
data = val;
next = prev = nullptr;
}
};
// Definition of Doubly Linked List class
class DoublyLinkedList {
private:
Node* head;
public:
DoublyLinkedList() {
head = nullptr;
}
void append(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
}
else {
Node* curr = head;
while (curr->next != nullptr) {
curr = curr->next;
}
curr->next = newNode;
newNode->prev = curr;
}
}
bool moveHead(int position) {
if (position < 0)
return false;
if (position == 0)
return true;
Node* curr = head;
int i = 0;
while (curr != nullptr && i < position) {
i++;
curr = curr->next;
}
if (curr == nullptr)
return false;
// Detach curr from its previous position
if (curr->prev != nullptr) {
curr->prev->next = curr->next;
}
if (curr->next != nullptr) {
curr->next->prev = curr->prev;
}
// Move curr to head
if (head != nullptr) {
Node* tail = head;
while (tail->next != nullptr) {
tail = tail->next;
}
tail->next = head;
head->prev = tail;
}
head = curr;
head->prev = nullptr;
return true;
}
void printList() {
Node* curr = head;
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
};
int main() {
DoublyLinkedList dll;
// Append some elements to the doubly linked list
dll.append(1);
dll.append(2);
dll.append(3);
dll.append(4);
dll.append(5);
cout << "Original list: ";
dll.printList();
int position = 2;
if (dll.moveHead(position)) {
cout << "After moving head to position " << position << ": ";
dll.printList();
}
else {
cout << "Failed to move head to position " << position << endl;
}
return 0;
}