通用权利转移

时间:2016-04-26 04:51:18

标签: c++ data-structures generic-programming

我收到了以下作业问题:

给定一组'n'个元素和'r',写一个通用函数,将元素集右移'r'位置。如果元素移动到大于'n'的位置,则将移位过程包装到集合的开头。例如,如果五个元素的集合是1,7,8,9,12并且'r'的值是3那么元素集将是8,9,12,1,7。

我觉得这个问题对循环队列的影响很大,所以我用它编写了一个代码。现在它不包含任何通用函数,但这不是问题,我的问题是我的shift函数没有正确地移动元素。请帮我一把。

#include<iostream>
#include<string>
using namespace std;
#define max 10

int q[max];
int front,rear;

void init() {
    front = -1;
    rear = -1;
}

void enqueue(int x) {
    if(front == (rear+1)%max) {
        cout<<"Queue overflow";
    }

    if(front == -1) {
        front = 0;
        rear = 0;
    }
    else {
        rear = (rear+1)%max;
    }
    q[rear]=x;
    //cout<<"Front"<<front<<endl;
    //cout<<"Rear"<<rear<<endl;
}

int dequeue() {
    int x;
    if(front == -1) {
        cout<<"Queue Underflow";
    }
    else {
        x = q[rear];
        rear = (rear+1)%max;
    }
    return x;
}

void display() {
    int i;
    if(front == -1) {
        cout<<"Queue Underflow";
    }
    else {
        for(i = front; i != rear; i =( i+1)%max) {
            cout<<q[i]<<'\t';
        }
        cout<<q[rear]<<endl;
    }
}

void shift(int num) {
    //do the shifting business here
    int i,x,r;
    cout<<"Enter by how many positions should the elements be shifted towards the right"<<endl;
    cin>>r;
    for(i = 0; i < (num-r); ++i) {
        x = dequeue();
        enqueue(x);
    }
}

int main() {
    int ch,n,i,x,r;
    init();
    //cout<<"Enter your choice"<<endl;
    //cin>>ch;
    cout<<"Number of elements in the collection"<<endl;
    cin>>n;

    for(i = 0; i < n; ++i) {
        cout<<"Enter the value to be added"<<endl;
        cin>>x;
        enqueue(x);
    }
    cout<<"The elements to be shifted"<<endl;
    display();
    shift(n);
    display();
}

修改

我给出的输入是:

元素数量: 5

要转移的元素: 1 7 8 9 12

元素应移动的值: 3

预期产出:

8 9 12 1 7

我得到的输出:

1 7 8 9 12 0 12 0 12

1 个答案:

答案 0 :(得分:0)

您的错误位于dequeue()。你需要前进指针,而不是后部:

int dequeue() {
    int x;
    if(front == -1) {
        cout<<"Queue Underflow";
    }
    else {
        x = q[front];
        front = (front+1)%max;
    }
    return x;
}