1. 算法要求
設将n(n>1)個整數存放到一維數組R中,試設計一個在時間和空間兩方面盡可能有效的算法,将R中保有的序列循環左移P(0﹤P﹤n)個位置,即将R中的資料由(X0 X1 ……Xn-1)變換為(Xp Xp+1 ……Xn-1 X0 X1 ……Xp-1)。
2. 算法思想
考慮使用隊列來實作,将隊列前面p個元素依次出隊列,再從隊尾部依次進隊列,即可實作該算法。使用資料結構:
[cpp] view plain copy
- typedef struct qnode{
- elemtype *base;
- int front;
- int rear;
- }sqqueue;
3. 算法實作
[cpp] view plain copy
- int in_sqqueue(sqqueue *sq, elemtype e)
- {
- if ((sq->rear + 1) % MAXQSIZE == sq->front)
- return ERROR;
- sq->base[sq->rear] = e;
- sq->rear = (sq->rear + 1) % MAXQSIZE;
- return OK;
- }
[cpp] view plain copy
- int out_sqqueue(sqqueue *sq, elemtype *e)
- {
- if (sq->front == sq->rear)
- return NULL_QUEUE;
- *e = sq->base[sq->front];
- sq->front = (sq->front + 1) % MAXQSIZE;
- return OK;
- }
[cpp] view plain copy
- void circle_left_shift_queue(sqqueue *sq, int n)
- {
- int i;
- elemtype e;
- for (i=0; i<n; ++i) {
- out_sqqueue(sq, &e);
- in_sqqueue(sq, e);
- }
- }
算法實作源碼: http://download.csdn.net/detail/algorithm_only/3892452