用数组方法实现堆栈,栈顶在上,栈底在下。
struct _Stack{
Item* elem; //数组元素
int top; //栈顶
int nMax; //大小
};
typedef struct _Stack Stack;
typedef Stack* pStack;
pStack Stack_Init(int nMax)
{
pStack pSt=malloc(sizeof(Stack));
pSt->elem=malloc(nMax*sizeof(Item));
pSt->top=-1;
pSt->nMax=nMax-1;
return pSt;
}
void Stack_Destroy(pStack pSt)
{
free(pSt->elem);
pSt->elem=NULL;
free(pSt);
pSt=NULL;
}
void Stack_Push(pStack pSt,Item elem)
{
if(Stack_IsFull(pSt))
{
Error("Stack Is Full");
exit(-1);
}
pSt->elem[++pSt->top]=elem;
}
Item Stack_Pop(pStack pSt)
{
if(Stack_IsEmpty(pSt))
{
Error("Stack Is Empty");
exit(-1);
}
return pSt->elem[pSt->top--];
}
int Stack_Size(pStack pStk)
{
return pStk->top+1;
}
BOOL Stack_IsEmpty(pStack pSt)
{
return pSt->top==-1;
}
BOOL Stack_IsFull(pStack pSt)
{
return pSt->top==pSt->nMax ;
}
==============================================================================================
假设我们从一个设备器件获取到的数据必须保证连续才能使用,如何知道它连续不连续呢?举一个实例,假设HRD_Data[8]是连续累加的值,在0-255循环。
typedef struct { u8 countnum; //传输的数据帧数目 ppg_mems_data_t data[FIFO_SIZE]; }ppg_mems_data_package; static ssize_t ofn_read(struct file *filp,char *buf,size_t count,loff_t *l) { ppg_mems_data_package buffer; memset(&buffer,0,sizeof(buffer)); static u8 HRD_Data8,HRD_Data8_bak; u8 datacount = 0; if(_write_index == (_read_index)) //无数据可传输 { PRINT(" ofn_read ============== ofn_read read empty !!! \n"); return 0; } while(_write_index != _read_index){ buffer.data[datacount] = _ppg_mems_data[_read_index]; PRINT(" ofn_read TEST hrd8<<<<<<<<<<<<<< (%3d) \n", _ppg_mems_data[_read_index].HRD_Data[8]); { //判断是否连续 HRD_Data8 = _ppg_mems_data[_read_index].HRD_Data[8]; if(HRD_Data8 != ((HRD_Data8_bak+1)%256)) PRINT(" ofn_read report not continus,HRD_Data8 is %3d, HRD_Data8_bak+1 is %3d \n",HRD_Data8,HRD_Data8_bak+1); HRD_Data8_bak = HRD_Data8; } _read_index++; //接收下一个数据 _read_index &= FIFO_SIZE_M1; datacount++; //接收下一个数据 } buffer.countnum = datacount; //共接收了多少个数据 copy_to_user(buf, &buffer,sizeof(buffer)/*count*/) ; return 1; }
参考原文:http://blog.csdn.net/ahljjun/archive/2008/11/11/3273452.aspx