【发布时间】:2014-02-06 15:24:28
【问题描述】:
我遇到过一种情况,我必须实现一个队列类型的数据结构。是这样的:
(1)假设有一个数组data[50]= {1,2,3,4,5,6};
(2) int Front 必须指向第一个索引,int back 必须指向最后一个索引。
(3)现在我必须添加这个数组的第一个和第二个元素。假设我这样做 (i+2=3) 并且这个 3 最终将通过执行后置+1 (data[rear+1]) 来设置,现在当第二次执行发生时,我们不必考虑前两个元素(他们已经添加了),所以在这种情况下我们可以做 data[front+2]。 但请注意,因为这个+2只会在第一次完成,之后就只是+1(因为我们只添加了一个元素,而我们第一次添加了2个元素) .并且添加时获得的元素必须到达索引的最后一个,例如获得的“3”最终会像这样{1,2,3,4,5,6,3}。
(4)所以我们要考虑到
(4.a) 每次添加后,Rear 加一。
(4.b) Front 加一(接受我们添加两个元素的第一个添加)。
(5) 我的想法如下:
#include <stdio.h>
#define MAX 50
int data[MAX];
int rear = - 1;
int front = - 1;
void main()
{
int rear=6, front=0;
data[size]={1,2,3,4,5,6};
int count=size;
//First do addition of the first two elements
data[rear]= data[0]+data[1];
for(i=front; i<size*2-1 ; i++) //we are doing data*2-1 because we know the final obtained on doing all the addition until there is 1 element will have the size (size*2-1).
{
do
{
//here we do addition data[rear+1]=data[front]+data[rear];
// rear++;
count--;
}while (count>1);
}
for(i=0; i<size*2-1 ; i++)
{
printf("%d ", data[i]); //Now this must print "1,2,3,4,5,6,3,6,9,12,21" (addition of element at front and rear)
}
}
**我的疑问是如何在第一次添加前增加两个,并在第一次添加后增加一个,这样 first 将始终指向要添加的元素(增加并不难,我已经做到了)。 请帮助我进行前端增量,算法和代码将非常感激。
【问题讨论】:
-
没有
size,并且有多种方法来解决循环缓冲区中的full-vs-empty检测问题。 Some of them here. -
@WhozCraig 对不起,我仍然无法理解,你刚刚说了什么。能否请您详细解释一下。
标签: c arrays algorithm data-structures queue