
今天学习了利用数组方式的栈的C++实现,这种方式跟指针实现有很多不一样的地方:
栈的指针实现,栈的创建申请头结点,push需要申请新的结点,pop释放结点,这些结点都放在第一个位置,top时,S->next->data即可。
栈的数组实现,只申请一个结点,该结点的结构体内包含,数组的最大容量、栈顶元素下标、指向整形数组的指针(用于存放和删除新的元素)。
S->topOfStack == -1,空栈;
S->topOfStack == S->capacity - 1,满栈;
1、声明结点
struct Node
{
int capacity; //数组的最大容量
int topOfStack; //栈顶下标为-1表示空栈,每次添加新的元素,栈顶元素下标加1
int *Array; //指向整形数组的指针
};
typedef struct Node stack;
2、空栈,满栈判断
int stackArray::isEmpty(stack *S)
{
return S->topOfStack == emptyTOS;
}
int stackArray::isFull(stack *S)
{
return S->topOfStack == S->capacity - ;
}
3、创建栈
stackArray::stack *stackArray::createStack(int maxElements)
{
if (maxElements < minStackSize)
cout << "the space of stack is too short,please increase value of maxElements!" << endl; stack *S;
S = (stack*)new(stack);
if (S == NULL)
cout << "Out of space! " << '\n'; S->Array = new int[maxElements];
if (S->Array == NULL)
cout << "Out of space! " << '\n'; S->topOfStack = emptyTOS; //栈顶下标置-1表示空栈
S->capacity = maxElements; //数组最大容量赋值
makeEmpty(S);
return S;
}
5、push,top,pop
stackArray::stack *stackArray::push(stack *S)
{
if (isFull(S))
{
cout << "stack is full!" << endl;
return ;
}
int x = ;
cout << "Please input the data to push: " << endl;
scanf_s("%d", &x);
S->Array[++S->topOfStack] = x;
return S;
}
int stackArray::top(stack *S)
{
if (isEmpty(S)) //非空判断
{
cout << "empty stack! " << endl;
return -;
}
else
return S->Array[S->topOfStack];
}
stackArray::stack *stackArray::pop(stack *S)
{
if (isEmpty(S)) //非空判断
{
cout << "empty stack! " << endl;
return ;
}
else
{
S->topOfStack--;
return S;
}
}
6、主函数
int main(int argc, char * argv[])
{
cout << '\n' << "***************************************" << '\n' << '\n';
cout << "Welcome to the stackArray world! " << '\n';
cout << '\n' << "***************************************" << '\n' << '\n'; int i = ;
int j = ;
int topElement = ;
stackArray *a = new stackArray;
stackArray::stack *S = NULL;
//int x = 0;
while (i)
{
cout << '\n' << "***************************************" << '\n';
cout << " 0 : end the stack " << '\n';
cout << " 1 : creat a stack " << '\n';
cout << " 2 : display the top element of stack " << '\n';
cout << " 3 : push a node in the stack " << '\n';
cout << " 4 : pop a node from the stack " << '\n';
cout << "***************************************" << '\n';
cout << "Please input the function your want with the number above : " << '\n';
scanf_s("%d", &j); switch (j)
{
case :
cout << "CreatStack now begin : ";
S = a->createStack();
break;
case :
topElement = a->top(S);
cout << "The top element of stack is : " << topElement;
break;
case :
cout << "push now begin : ";
S = a->push(S);
break;
case :
cout << "pop now begin : ";
S = a->pop(S);
break;
default:
cout << "End the stack. ";
a->disposeStack(S);
i = ;
break;
} } return ;
}
效果同指针,不再赘述。