单数组实现双端队列

来源:互联网 发布:mysql显示当前时间指令 编辑:程序博客网 时间:2024/06/05 03:13
#include<stdio.h>#include<iostream>using namespace std;int i = 0;void push_head(int *a, int d) {//头部插入元素   for(int j = i-1; j >= 0; j--) a[j+1] = a[j];//遍历往后推一个   a[0] = d;  i++;}void push_end(int *a, int d) { a[i++] = d; }void pop_head(int *a) {  if(a[i-1] == 0) cout << "队列已空\n";  else {    for(int j = 0; j <= i; j++) a[j] = a[j+1];//遍历往前推一个     i--;  }}void pop_end(int *a) {  if(a[i-1] == 0) cout << "队列已空\n";  else {    a[i-1] = 0;    i--;  }}void show(int *a) {  cout << "该队列的元素";    for(int i = 0; i < 1000; i++) {      if(a[i] != 0)         printf("a[%d] = %d ", i, a[i]);    }  cout << endl;}int main() {  int d, a[10000];  string s;  while(cin >> s) {    if(s == "push_end") { cin >> d; push_end(a, d); show(a); } //末尾增加一个d    if(s == "push_head") { cin >> d; push_head(a, d); show(a); }//头部增加一个d     if(s == "pop_head") { pop_head(a); show(a); }//删除头部元素     if(s == "pop_end") { pop_end(a); show(a); }//删除尾部元素   }}

0 0
原创粉丝点击