Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <exception>
- #include <iostream>
- class LinkedList {
- private:
- struct Element {
- Element* next = nullptr;
- Element* prev = nullptr;
- int data = 0;
- Element(int data) {
- this->data = data;
- }
- };
- Element* head = nullptr;
- Element* tail = nullptr;
- int length = 0;
- Element* NodeAt(int n) {
- if (n > this->length - 1 || n < 0) {
- throw std::exception("Index is out of bounds");
- }
- else {
- Element* pivot = this->head;
- int c = 0;
- while (c!=n) {
- pivot = pivot->next;
- c++;
- }
- return pivot;
- }
- }
- void remove(Element* that) {
- if (that == this->head) {
- this->head = this->head->next;
- }
- else if(that == this->tail) {
- this->tail->prev->next = nullptr;
- this->tail = this->tail->prev;
- }else{
- std::cout << this->head << " " << that << " " << this->tail << std::endl;
- that->prev->next = that->next;
- that->next->prev = that->prev;
- }
- this->length--;
- }
- public:
- int size() {
- return this->length;
- }
- int at(int n) {
- return NodeAt(n)->data;
- }
- void push_back(int data) {
- if (this->length == 0) {
- this->head = new Element(data);
- this->tail = this->head;
- }
- else {
- this->tail->next = new Element(data);
- this->tail->next->prev = this->tail;
- this->tail = this->tail->next;
- }
- this->length++;
- }
- int operator[](int n) {
- return at(n);
- }
- //Удаляет элемент по индексу
- int remove_at(int n) {
- if (n > this->length - 1 || n < 0) {
- throw std::exception("Index is out of bounds");
- }
- else {
- if (n == 0) {
- int result = this->head->data;
- this->head = this->head->next;
- return result;
- }
- else {
- Element* that = this->NodeAt(n);
- int result = that->data;
- that->prev->next = that->next;
- that->next->prev = that->prev;
- return result;
- }
- }
- this->length--;
- }
- //Расширение стандартного интерфейса связного списка
- //Удаляет элемент по значению
- void remove_by(int a) {
- Element* pivot = this->head;
- while(pivot != nullptr) {
- if (pivot->data == a) {
- Element* deletable = pivot;
- pivot = pivot->next;
- this->remove(deletable);
- }
- else {
- pivot = pivot->next;
- }
- }
- this->length--;
- }
- //Минимальный элемент списка
- int min() {
- int minima = INFINITY;
- Element* pivot = this->head;
- while (pivot != nullptr) {
- if (pivot->data < minima) {
- minima = pivot->data;
- }
- }
- return minima;
- }
- std::string ToString() {
- std::string s;
- Element* pivot = this->head;
- while (pivot != nullptr) {
- s += std::to_string(pivot->data) + " ";
- pivot = pivot->next;
- }
- return s;
- }
- };
- int main()
- {
- LinkedList list;
- int n = 0;
- std::cin >> n;
- for (int i = 0; i < n; i++) {
- int a;
- std::cin >> a;
- list.push_back(a);
- }
- int min = list.min();
- list.remove_by(min);
- std::cout << list.ToString() << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement