Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sstream>
- #include <string>
- using namespace std;
- struct Node {
- string value;
- Node *next;
- Node(string _value, Node *_next = nullptr)
- : value(_value), next(_next) {}
- };
- struct List {
- Node *root = nullptr;
- string toString() {
- Node *current = this->root;
- ostringstream sstream;
- sstream << "[";
- if (current == nullptr) {
- sstream << "]";
- }
- while (current != nullptr) {
- sstream << current->value;
- current = current->next;
- if (current == nullptr) {
- sstream << "]";
- } else {
- sstream << ", ";
- }
- }
- return sstream.str();
- }
- int length() {
- int length = 0;
- Node *current = this->root;
- while (current != nullptr) {
- length++;
- current = current->next;
- }
- return length;
- }
- Node* last() {
- Node *current = this->root;
- while (current != nullptr) {
- if (current->next == nullptr) {
- return current;
- }
- current = current->next;
- }
- return nullptr;
- }
- void add(string value) {
- Node *_new = new Node(value);
- Node *last = this->last();
- if (last == nullptr) {
- this->root = _new;
- } else {
- last->next = _new;
- }
- }
- Node* nodeAt(int index) {
- Node* current = this->root;
- for (
- int i = 0;
- i != index && current != nullptr;
- i++, current = current->next
- );
- return current;
- }
- Node* findNode(string value) {
- Node* current = this->root;
- for (;
- current != nullptr && current->value != value;
- current = current->next
- );
- return current;
- }
- // Задание 1-Н
- void removeAllAfter(string value) {
- Node* node = this->findNode(value);
- if (node != nullptr) {
- node->next = nullptr;
- }
- }
- // Задание 2-А
- void replaceAt(int k, string value) {
- Node* node = this->nodeAt(k);
- if (node != nullptr) {
- node->value = value;
- }
- }
- // Задание 3-А
- int countStartingWith(char letter) {
- int count = 0;
- for (
- Node* current = this->root;
- current != nullptr;
- current = current->next
- ) {
- if (current->value[0] == letter) {
- count++;
- }
- }
- return count;
- }
- // Задание 4-В
- string* toArray(int k) {
- string* arr = new string[k];
- Node* current = this->root;
- for (
- int i = 0;
- i < k && current != nullptr;
- i++, current = current->next
- ) {
- arr[i] = current->value;
- }
- return arr;
- }
- };
- int main() {
- List list;
- list.add("ABC");
- list.add("ACD");
- list.add("DBC");
- list.add("BCD");
- list.add("XYZ");
- cout << list.toString() << " [" << list.length() << "]" << endl;
- list.removeAllAfter("DBC");
- cout << list.toString() << " [" << list.length() << "]" << endl;
- list.replaceAt(2, "dbc");
- cout << list.toString() << " [" << list.length() << "]" << endl;
- cout << "Starting with A: " << list.countStartingWith('A') << endl;
- string* arr = list.toArray(2);
- for (int i = 0; i < 2; i++) {
- cout << "> [" << i << "]: " << arr[i] << endl;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement