Skip to content

Instantly share code, notes, and snippets.

@tinylamb
Created December 11, 2013 17:00
Show Gist options
  • Select an option

  • Save tinylamb/7914321 to your computer and use it in GitHub Desktop.

Select an option

Save tinylamb/7914321 to your computer and use it in GitHub Desktop.
小程序:一列数[1 2 2 6 10 11 10 15 15...],相邻两数之间的距离小于2时,将其做平均,且输出。 输入:[1 2 2 6 10 11 10 15 15...] 输出:[5/3 ,6 , 31/3 , 15]
#include <stdio.h>
#include <stdlib.h>
#define STACKSIZE 10 /* 用栈存储不满足条件数,下一次输入从栈开始 */
#define QUEUESIZE 100 /* 用队列存储输入 */
#define N 100 /* 存储输出结果的数组大小 */
#define Emptystack(s) s.top==0
#define Emptyqueue(q) q.count==0
#define GAP 2
/*---------------------------------------------------
* 栈操作:声明栈sta 及相应的压栈 出栈操作
*---------------------------------------------------*/
typedef struct stack Stack;
struct stack{
int stack[STACKSIZE];
int top;
};
Stack sta;
void push(int i);
int pop();
/*---------------------------------------------------
* 队列操作:声明队列que 及相应的入队 出队操作
*---------------------------------------------------*/
typedef struct queue Queue;
struct queue{
int queue[QUEUESIZE];
int head,tail,count;
};
Queue que;
void inque(int i);
int deque();
/*---------------------------------------------------
* 读取下一个数,如果栈非空就从栈中读取,否则从队列读取
*---------------------------------------------------*/
int geti();
int main(){
float b[N];
int i;
sta.top=0;
que.head=que.tail=que.count=0;
while(scanf("%d",&i)==1)
inque(i);
int prenum=0,num,len=0,j=0; /* num指当前读入的数,prenum指前一个读入的数,len记录符合间隔的数的个数 */
float sum=0.0;
while(!Emptystack(sta) || !Emptyqueue(que)){ /* 这里是程序的关键 */
num=geti();
if(len==0 || (num-prenum<GAP && num-prenum >-GAP)){ /* 如果读入的数与之前数间隔<2 则保存这些数的和 */
sum+=num;
len++;
prenum=num;
}
else{ /* 一旦出现读入的数与前一个数间隔>=2 就将这个数压栈,并保存之前符合要求的数的均值到数列b[N]中 */
push(num);
b[j++]=sum/len;
sum=0.0;
len=0;
prenum=0;
}
}
b[j++]=sum/len;
for(i=0;i<j;i++)
printf("%.3f%s",b[i],(i==j-1)?"\n":" ");
return 0;
}
void push(int i){
sta.stack[sta.top]=i;
sta.top++;
}
int pop(){
if(sta.top!=0)
return sta.stack[--sta.top];
else
exit(0);
}
void inque(int i){
que.queue[que.tail++]=i;
que.count++;
}
int deque(){
if(que.count!=0){
int i=que.queue[que.head];
que.head++;
que.count--;
return i;
}
else
exit(0);
}
int geti(){
if(!Emptystack(sta))
return pop();
else if(!Emptyqueue(que))
return deque();
else
exit(0);
}
@tinylamb
Copy link
Copy Markdown
Author

io stream 类似一个队列?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment