这是自定义简易栈内部源码
// 栈内部实现
typedef struct Node2
{
int data;
struct Node2 *pNext;
}NODE2, *PNODE2;
typedef struct Stack
{
PNODE2 top;
PNODE2 bottom;
}STACK, *PSTACK;
void initStack(PSTACK stack);
bool is_EmptyStack(PSTACK stack);
bool traVelStack(PSTACK stack);
int lenghtStack(PSTACK stack);
bool pushStack(PSTACK stack, int value);
bool popStack(PSTACK stack, int *value);
int main()
{
int value;
STACK stack;
initStack(&stack);
is_EmptyStack(&stack);
pushStack(&stack, 34);
pushStack(&stack, 23);
pushStack(&stack, 234);
pushStack(&stack, 114);
pushStack(&stack, 24);
pushStack(&stack, 204);
traVelStack(&stack);
popStack(&stack, &value);
traVelStack(&stack);
return 0;
}
// 栈内部实现
void initStack(PSTACK stack)
{
stack->top = (PNODE2)malloc(sizeof(NODE2));
if (NULL == stack->top) {
printf("内存分配失败\n");
return;
}
stack->bottom = stack->top;
stack->top->pNext = NULL;
return;
}
bool is_EmptyStack(PSTACK stack)
{
if (stack->top == stack->bottom) {
printf("栈为空\n");
return true;
}
return false;
}
bool traVelStack(PSTACK stack)
{
// if (is_EmptyStack(stack)) return false;
PNODE2 newNode = stack->top;
int i = 0;
while (newNode != stack->bottom) {
printf("%d ",newNode->data);
newNode = newNode->pNext;
++i;
}
printf("\n");
return true;
}
int lenghtStack(PSTACK stack)
{
if (is_EmptyStack(stack)) return false;
PNODE2 newNode = stack->top;
int i = 0;
while (NULL == newNode->pNext) {
// printf("%d",newNode->data);
newNode = newNode->pNext;
++i;
}
printf("栈的长度为:%d\n",i);
return i;
}
bool pushStack(PSTACK stack, int value)
{
PNODE2 node_New = (PNODE2)malloc(sizeof(NODE2));
if (NULL == node_New) {
printf("入栈失败\n");
return false;
}
node_New->pNext = stack->top;
node_New->data = value;
stack->top = node_New;
return true;
}
bool popStack(PSTACK stack, int *value)
{
if (is_EmptyStack(stack)) return false;
PNODE2 node_New = stack->top;
stack->top = node_New->pNext;
free(node_New);
return true;
}