利用顺序栈的基本操作,将元素A、B、C、D、E、F、G、H依次入栈,再将栈顶元素即H和G出栈,然后把X和Y入栈,最后将元素全部出栈,并依次输出出栈元素。
写出程序设计思想和主要代码解释
#include <vector> #include <iostream> using namespace std; int main(){ vector<char> stack; int i = 0; int total = 0; stack.push_back('A'); stack.push_back('B'); stack.push_back('C'); stack.push_back('D'); stack.push_back('E'); stack.push_back('F'); stack.push_back('G'); stack.push_back('H'); cout << stack.back(); stack.pop_back(); cout << stack.back(); stack.pop_back(); stack.push_back('X'); stack.push_back('Y'); total = stack.size(); for (i = 0; i <total; i++){ cout << stack.back(); stack.pop_back(); } system("pause"); return 0; }
#include <stdlib.h> #include <stdio.h> #define MAX 10 typedef char ElemType; typedef struct Stack{ ElemType data[MAX]; int top; //栈顶 int length; //栈的大小 }Stack, *pStack; //初始化栈 void init(pStack stack){ stack->top = -1; //由于数组索引是从0开始的,栈中没有数据时,栈顶的索引就是-1 stack->length = 0; //栈的初始长度为0 } //入栈 int push(pStack stack, ElemType num){ if(stack->length>=MAX ){ //判断栈的长度是否大于栈的最大容量。 printf("---栈满溢出,添加失败.\n"); return 0; } stack->top++; //栈顶索引上移加1. stack->data[stack->top]=num; //将栈元素压入到栈中。 stack->length++; //栈的长度加1. printf("---%c入栈\n",num); return 1; } //出栈 ElemType pop(pStack stack){ if(stack->length<=0){ //判断栈中是否存在元素。 printf("---没有可输出的元素\n"); return 0; } ElemType ch = stack->data[stack->top]; //输出栈元素。 printf("---%c出栈\n",ch); stack->length--; //栈的长度减1. stack->top--; //栈顶索引下移减1. return ch; } int main(){ ElemType num; Stack s; init(&s); push(&s, 'A'); push(&s, 'B'); push(&s, 'C'); push(&s, 'D'); push(&s, 'E'); push(&s, 'F'); push(&s, 'G'); push(&s, 'H'); pop(&s); pop(&s); push(&s, 'X'); push(&s, 'Y'); ElemType c; while ((c=pop(&s))) { printf("输出%c\n", c); } return 0; }