Вот мой код
Код: Выделить всё
class Node {
public:
T data;
Node *next;
Node *prev;
friend class DLinkedList;
public:
Node(Node *next = 0, Node *prev = 0) {
this->next = next;
this->prev = prev;
}
Node(T data, Node *next = 0, Node *prev = 0) {
this->data = data;
this->next = next;
this->prev = prev;
}
};
template
void DLinkedList::addNode(T e) {
// TODO implement
//add at the end
Node *newNode = new Node(e, tail, tail->prev);
tail->prev->next = newNode;
tail->prev = newNode;
count++;
}
template
void DLinkedList::addAt(int index, T e) {
// TODO implement
if (index < 0 || index > count)
{
throw std::out_of_range("Index is out of range!");
}
if (index == count || count == 0)
{
addNode(e);
return;
}
Node *prevNode = getPreviousNode(index);
Node *newNode = new Node(e, prevNode->next, prevNode);
if (index == 0) {
// Inserting at the head
newNode->next = head->next;
newNode->prev = head;
if (head->next != nullptr) {
head->next->prev = newNode;
}
head->next = newNode;
}
if (prevNode->next) {
prevNode->next->prev = newNode;
}
prevNode->next = newNode;
count++;
}
template
typename DLinkedList::Node *DLinkedList::getPreviousNode(int index) {
/**
* Returns the node preceding the specified index in the doubly linked list.
* If the index is in the first half of the list, it traverses from the head;
* otherwise, it traverses from the tail. Efficiently navigates to the node by
* choosing the shorter path based on the index's position.
*/
// TODO implement
if (index < 0 || index > count)
{
throw std::out_of_range("Index is out of range!");
}
Node *current = nullptr;
if (index == 0) {
return head;
} else if (index < count / 2) {
current = head;
for (int i = 0; i < index; i++) {
current = current->next;
}
} else {
current = tail;
for (int i = count; i > index; i--) {
current = current->prev;
}
}
return current->prev;
}
Код: Выделить всё
list.add(0);
list.add(0, 1);
list.add(1, 2);
list.add(3, 3);
list.add(2, 4);
list.add(4, 5);
list.add(6);
list.add(6, 7);
list.add(0, 8);
list.add(1, 9);
list.add(2, 10);
Ожидается: [8, 9, 10, 1, 2, 4, 0, 5, 3, 7, 6]
У меня [8, 10, 9, 1, 2, 4, 0, 5, 3, 7, 6]
Подробнее здесь: https://stackoverflow.com/questions/790 ... -list-with