include iostream include ctime using namespace std struct ListNode int

  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
#include <iostream>
#include <ctime>
using namespace std;
struct ListNode
{
int value;
ListNode* next = nullptr;
};
ListNode* getRandomList(int size);
void printList(ListNode* element);
int findKey(ListNode* element, int key);
void removeElement(ListNode* element, int index);
void swapWithNext(ListNode* element, int index);
void appendReversedList(ListNode* element);
int main() {
ListNode* list = getRandomList(10);
printList(list);
int key;
std::cout << "Key :";
std::cin >> key;
int index = findKey(list, key);
removeElement(list, 0);
swapWithNext(list, index);
printList(list);
appendReversedList(list);
printList(list);
system("pause");
return 0;
}
ListNode* getRandomList(int size) {
ListNode* list = new ListNode;
ListNode* element = list;
srand((unsigned)time(0));
for (int i = 0; i < size; i++) {
element->value = rand();
element->next = new ListNode;
element = element->next;
}
return list;
}
void printList(ListNode* element) {
while (element->next != nullptr) {
cout << element->value << " ";
element = element->next;
}
cout << endl;
}
int findKey(ListNode* element, int key) {
int index = 0;
while (element->value != key && element->next != nullptr) {
index++;
element = element->next;
}
return index;
}
void removeElement(ListNode* element, int index) {
for (int i = 0; i < index; i++) {
element = element->next;
}
if (index = 0) {
ListNode* temp = element;
delete
}
}
void swapWithNext(ListNode* element, int index) {
for (int i = 0; i < index && element != nullptr; i++) {
element = element->next;
}
if (element != nullptr && element->next != nullptr) {
int temp_value = element->next->value;
element->next->value = element->value;
element->value = temp_value;
}
}
void appendReversedList(ListNode* element) {
ListNode* reversed_list = new ListNode;
reversed_list->value = element->value;
reversed_list->next = nullptr;
/*while (element->next != nullptr) {
ListNode* temp_element = new ListNode;
temp_element->next = reversed_list;
temp_element->value = element->next->value;
reversed_list = temp_element;
element = element->next;
}*/
element->next = reversed_list;
}