Untitled

mail@pastecode.io avatar
unknown
c_cpp
6 months ago
2.1 kB
1
Indexable
Never
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
};

Node *head = NULL;
Node *tail = NULL;
Node *prevNode = NULL;
Node *vec_pt[10005];
int vec[10005];
int head_data = 0;
bool isReverse = false; // if j >= n-1, then reverse the whole list
int n;
unsigned long long j;

void reverse() {
    int tmp = 0;
    if(isReverse == true) {
        for(int i = 0; i < n; i++) {
            vec_pt[i] = tail;
            vec[i] = tail->data;
            tail = tail->next;
        }
        for(int i = n - 1; i >= 0; i--) {
            if(vec[i] == head_data)
                head = vec_pt[tmp];
            vec_pt[tmp++]->data = vec[i];
        }
        isReverse = false;
    }
    else {
        for(int i = j - 1; i >= 0; i--) {
            vec_pt[tmp++]->data = vec[i];
        }
    }
}

void print() {
    Node* current = head;
    for(int i = 0; i < n-1; i++) {
        cout << current->data << " ";
        current = current->next;
    }
    cout << current->data << endl;
}

int main() {
    cin >> n;
    // create circular linked list
    for(int i = 0; i < n; i++) {
        Node* node = new Node;
        cin >> node->data;
        if(prevNode == NULL) { 
            head = node;
            prevNode = node;
        }
        prevNode->next = node; 
        prevNode = node; 
    }
    prevNode->next = head;

    while (cin >> j) {
        if(j == -1) break;
        else if(j % n == 0) // notice this case!!
            j = n;
        else if(j >= n-1) { 
            isReverse = true;
            j = j % n;
        }

        // record which node gets bomb
        tail = head;
        for(int i = 0; i < j; i++) {
            if(isReverse == false) {
                vec_pt[i] = tail;
                vec[i] = tail->data;
            }
            prevNode = tail;
            tail = tail->next;
        }
        prevNode->next = tail->next;
        head = prevNode->next;
        head_data = head->data;
        delete tail;
        tail = head;

        n--;
        reverse();
        // print();
        if(n == 1) break;
    }
    print();
    return 0;
}