结构体里定义top与base的指针,命令行输入字符串,top指针里内容是字符串,top++是不改变字符串的
typedef struct sta{
ElemType *top;
ElemType *bottom;
int stack_size;
}SqStack;//顺序栈
int InitStack(SqStack *S)
{
S->bottom = (ElemType*)malloc(STACK_SIZE*sizeof(ElemType));
if (!S->bottom)
return ERROR;
S->top = S->bottom;
S->stack_size = STACK_SIZE;
return OK;
}//顺序栈的初始化
void PushSqStack(SqStack *S, ElemType *a)//顺序栈入栈
{
if ((S->top - S->bottom) >= S->stack_size - 1)//判断栈是否满
{
S->bottom = (ElemType*)realloc(S->bottom, sizeof(ElemType));//realloc的用法
if (!S->bottom)
return;
S->top = S->bottom + S->stack_size;
S->stack_size += STACKINCREMENT;
}
S->top= a;
S->top++;
}
int popSqStack(SqStack *S,int*e)//顺序栈出栈并返回栈顶值
{
if (S->top == S->bottom)
return ERROR;
else
{
--(S->top);
e = S->top;
}
return OK;
}
switch (temp)
{
case'1':
printf("顺序栈创建成功!\n");
int n, i;
printf("请输入你想要输入的个数:\n");
scanf("%d", &n);
printf("请输入:\n");
for (i = 0; i < n; i++)
{
ElemType *a;
a=(ElemType*)malloc(sizeof(ElemType));
scanf("%s",a);
PushSqStack(&S, a);
}
printf("入栈成功!\n");
break;
case'2':
printf("出栈依次为:\n");
while (S.bottom != S.top)
{
int *e;
e = (ElemType*)malloc(sizeof(ElemType));
popSqStack(&S,e);
printf("%s\n",e);
}
printf("出栈成功!\n");
break;
// ConsoleApplication12.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <malloc.h>
#include<iostream>
#include<string>
#include<iomanip>
#include<fstream>
#define _CRT_SECURE_NO_WARNINGS1
#define ERROR -1
#define OK 0
#define STACK_SIZE 100
#define STACKINCREMENT 10
#define QUEUE_SIZE 100
#define SIZE 30
using namespace std;
typedef char ElemType;
typedef struct sta{
ElemType *top;
ElemType *bottom;
int stack_size;
}SqStack;//顺序栈
int InitStack(SqStack *S)
{
S->bottom = (ElemType*)malloc(STACK_SIZE*sizeof(ElemType));
if (!S->bottom)
return ERROR;
S->top = S->bottom;
S->stack_size = STACK_SIZE;
return OK;
}//顺序栈的初始化
void PushSqStack(SqStack *S, ElemType *a)//顺序栈入栈
{
if ((S->top - S->bottom) >= S->stack_size - 1)//判断栈是否满
{
S->bottom = (ElemType*)realloc(S->bottom, sizeof(ElemType));//realloc的用法
if (!S->bottom)
return;
S->top = S->bottom + S->stack_size;
S->stack_size += STACKINCREMENT;
}
S->top= a;
S->top++;
}
int popSqStack(SqStack *S,int*e)//顺序栈出栈并返回栈顶值
{
if (S->top == S->bottom)
return ERROR;
else
{
--(S->top);
e = S->top;
}
return OK;
}
int _tmain(int argc, _TCHAR* argv[])
{
SqStack S;
InitStack(&S);
char temp;
int i;
i = 0;
temp = '0';
while (1)
{
if (temp == '0' || temp == '1' || temp == '2' ){
printf(" press 1 to 创建一个顺序栈并入栈\n");
printf(" press 2 to 从顺序栈出栈\n");}
temp = getchar();
switch (temp)
{
printf("顺序栈创建成功!\n");
int n, i;
printf("请输入你想要输入的个数:\n");
scanf("%d", &n);
printf("请输入:\n");
for (i = 0; i < n; i++)
{
ElemType *a;
a=(ElemType*)malloc(sizeof(ElemType));
scanf("%s",a);
PushSqStack(&S, a);
}
printf("入栈成功!\n");
break;
case'2':
printf("出栈依次为:\n");
while (S.bottom != S.top)
{
int *e;
e = (ElemType*)malloc(sizeof(ElemType));
popSqStack(&S,e);
printf("%s\n",e);
}
printf("出栈成功!\n");
break;
}
}
return OK;}