Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct Node {
- int data;
- Node* next;
- };
- struct List {
- Node* head = nullptr;
- Node* tail = nullptr;
- void add(int value) {
- Node* temp = new Node;
- temp->data = value;
- temp->next = nullptr;
- if (head == nullptr and tail == nullptr) {
- head = tail = temp;
- }
- else {
- tail->next = temp;
- tail = temp;
- }
- }
- //
- int getCount() {
- int count = 0;
- Node* current = head;
- while (current) {
- count++;
- current = current->next;
- }
- return count;
- }
- void reverse(int from, int to) {
- int count = getCount();
- to = min(to, count);
- if (from >= count || to == from || !head) {
- return;
- }
- Node* before = nullptr;
- Node* after = nullptr;
- if (from != 1) {
- before = head;
- for (int i = 2; i < from; i++)
- before = before->next;
- }
- if (to <= count) {
- after = head;
- for (int i = 0; i < to; i++)
- after = after->next;
- }
- Node* start = before ? before->next : head;
- Node* current = start;
- Node* next = current->next;
- while (next != after) {
- Node* newNext = next->next;
- next->next = current;
- current = next;
- next = newNext;
- }
- if (before)
- before->next = current;
- else
- head = current;
- if (after)
- start->next = after;
- else {
- tail = start;
- start->next = nullptr;
- }
- }
- void print() {
- Node* temp = head;
- while (temp) {
- cout << temp->data << " ";
- temp = temp->next;
- }
- cout << endl;
- }
- ~List() {
- Node* curr = head;
- while (curr) {
- Node* prev = new Node;
- prev = curr;
- curr = curr->next;
- delete prev;
- }
- delete curr;
- }
- };
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- List testList;
- int queries;
- cin >> queries;
- for (int t = 0; t < queries; t++) {
- string op;
- cin >> op;
- if (op == "add") {
- int num;
- cin >> num;
- testList.add(num);
- }
- if (op == "print") {
- testList.print();
- }
- if (op == "reverse") {
- int from, to;
- cin >> from >> to;
- testList.reverse(from, to);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment