0 / 0 / 0
Регистрация: 18.11.2020
Сообщений: 21
1

Сортировка списка списков

13.06.2021, 11:43. Показов 340. Ответов 0
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Для шаблонного класса List нужно создать метод, который поменяет местами максимальный и минимальный элемент в списке объектов класса CListDeleteFirstPositive.
C++
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
using namespace std;
bool isDouble(string s) {
    int m;
    if (s.find('-') != -1) {
        m = s.find('-');
        if ((s.find('-', m + 1) != -1) || (m != 0)) {
            return false;
        }
    }
    if (s.find('.') != -1) {
        m = s.find('.');
        if ((s.find('.', m + 1) != -1) || (m == 0)) {
            return false;
        }
    }
    if (s.find_first_not_of("0123456789.-") != -1) {
        return false;
    }
}
class CListDeleteFirstPositive
 
{
 
    struct list
 
    {
        int info;
        struct list* next;
    };
    struct list* head;
    struct list* tail;
public:
    CListDeleteFirstPositive();
    ~CListDeleteFirstPositive();
    void AddItem(int item);
    void DisplayList();
    void ReleaseList();
    void DeleteFirstPositive();
    friend istream& operator >> (istream& in, CListDeleteFirstPositive& l);
    friend ostream& operator << (ostream& out, CListDeleteFirstPositive& l);
};
ostream& operator << (ostream& out, CListDeleteFirstPositive& l) {
    l.DisplayList();
    return out;
}
istream& operator >> (istream& in, CListDeleteFirstPositive& l) {
    string temp;
    double tx;
    cin >> temp;
    while (temp[0] != '.') {
        stringstream ss;
        ss << temp;
        if ((ss.fail()) || (isDouble(temp) == false)) {
            cout << "Ошибка ввода" << endl;
        }
        else {
            ss >> tx;
            l.AddItem(tx);
        }
        cin >> temp;
    }
    return in;
}
CListDeleteFirstPositive::CListDeleteFirstPositive()
 
{
    head = NULL;
    tail = NULL;
}
 
CListDeleteFirstPositive::~CListDeleteFirstPositive()
{
    ReleaseList();
}
void CListDeleteFirstPositive::AddItem(int item)
{
 
    struct list* newItem;
    newItem = new struct list;
    newItem->info = item;
    if (tail == NULL)
    {
        head = newItem;
        tail = newItem;
        tail->next = NULL;
    }
    else
    {
        tail->next = newItem;
        tail = tail->next;
        tail->next = NULL;
    }
}
void CListDeleteFirstPositive::DisplayList()
{
 
    struct list* current = head;
    while (current != NULL)
    {
        printf("->%d", current->info);
        current = current->next;
    }
}
void CListDeleteFirstPositive::ReleaseList()
{
    if (head != NULL)
    {
        struct list* current;
        while (head != NULL)
        {
            current = head;
            head = head->next;
            delete current;
        }
        head = NULL;
        tail = NULL;
    }
}
void CListDeleteFirstPositive::DeleteFirstPositive()
{
    if (head != NULL)
    {
        struct list* current = head;
        struct list* temp = NULL;
        if (head->info > 0)
        {
            current = head;
            head = current->next;
            delete current;
            printf("Первый положительный элемент удалён.");
        }
 
        else
 
        {
 
            while (temp == NULL && current != NULL)
 
            {
 
                if (current->next->info > 0)
 
                {
 
                    temp = current;
 
                }
 
                current = current->next;
 
            }
 
            if (temp != NULL)
 
            {
 
                current = temp->next;
 
                temp->next = current->next;
 
                delete current;
 
                printf("Первый положительный элемент удалён.");
 
            }
 
            else
 
                printf("В списке нет положительных элементов.");
 
        }
 
    }
 
}
 
template <typename A>
class LIST {
    struct spisok {
        A* info;
        spisok* next;
    };
    spisok* head, tail;
    int count;
public:
    LIST() {
        head = NULL;
        tail = NULL;
    }
    ~LIST() {
        DestrList();
    }
    void DestrList()
 
    {
 
        if (head != NULL)
 
        {
 
            struct list* current;
 
            while (head != NULL)
 
            {
 
                current = head;
 
                head = head->next;
 
                delete current;
 
            }
 
            head = NULL;
 
            tail = NULL;
 
        }
 
    }
        void add(A* data) {
            spisok* temp = new spisok;
            temp->info = data;
            temp->next = NULL;
            if (head == NULL) {
                head = temp;
                tail = head;
            }
            else
            {
                tail->next = temp;
                tail = tail->next;
            }
            count++;
        }
 
        void DisplayList() {
            if (head == NULL) {
                cout << "Список пуст" << endl;
            }
            else
            {
                spisok* temp = head;
                while (temp) {
                    cout << *(temp->info);
                    if (temp->next != NULL)
                        cout << "=>";
                    else
                        cout << endl;
                    temp = temp->next;
                }
            }
        }
    void Change() {
        if (head != NULL)
        {
            spisok* current = head;
            spisok* max = head;
            spisok* min = head;
            while (current != NULL)
            {
                if (current->info > max->info)
                {
                    max = current;
                }
                if (current->info < min->info)
                {
                    min = current;
                }
                current = current->next;
            }
            spisok* temp = max;
            max = min;
            min = temp;
        }
        else {
            cout << "Список пуст" << endl;
        }
    }
};
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
13.06.2021, 11:43
Ответы с готовыми решениями:

Быстрая сортировка (сортировка Хоара) для связных списков
есть у кого готовый алгоритм? или подскажите как реализовать

Сортировка списков
Как можно из двух списков, допустим с фамилиями, вывести на экран так, чтобы первые были фамилии,...

Плавная сортировка списков (Smoothsort)
Требуется с помощью плавной сортировки (Smoothsort), отсортировать однонаправленый и двунаправленый...

Сортировка посредством слияния списков
Помогите пожалуйста написать алгоритм сортировки посредством слияния списков

0
13.06.2021, 11:43
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
13.06.2021, 11:43
Помогаю со студенческими работами здесь

Сортировка списков (Умножение полиномов)
Задача: Имеются 2 полинома (А и В). Они задаются, как массив коэффициентов при иксах. Нужно...

Сортировка линейных(односвязных) списков
Всем доброго времени суток. Уже на протяжении нескольких дней бьюсь с сортировкой линейных списков....

Программная реализация динамического списка динамических списков
Обучаюсь удаленно через интернет. И тут такая штука. Случайно нажал кнопку &quot;Сдать курсовую&quot;. А темы...

Сравнение 2-х списков и удаление одинаковых элементов из 2-го списка
# include &lt;iostream&gt; # include &lt;string&gt; # include &lt;fstream&gt; # include &lt;vector&gt; # include...

Организация списка списков
В классе имеется список указателей на списки QList&lt;QList&lt;Point3D&gt;*&gt; PointList; В методе я создаю...

Сортировка списка списков
Задание звучит так: Дан список, содержащий произвольные подсписки чисел. Написать программу,...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru