#include <stdio.h>
#include <stdlib.h>
/*实现链栈*/
typedef struct StackNode{
int data;
struct StackNode *next;
}StackNode;
/*初始化*/
StackNode * initStack(){
StackNode * stack;
stack -> next = (StackNode *)malloc(sizeof(StackNode));
stack -> next = NULL;
return stack;
}
/*入栈*/
int push(StackNode * stack,int elem){
StackNode * elemNode = (StackNode *)malloc(sizeof(StackNode));
elemNode -> data = elem;
elemNode -> next = stack -> next;
stack -> next = elemNode;
return 1;
}
/*出栈*/
int pop(StackNode * stack){
int topElem;
if(stack -> next == NULL) return 0;
StackNode * p = stack -> next;
topElem = stack -> next -> data;
stack -> next = stack -> next -> next;
free(p);
return topElem;
}
/*取栈顶元素*/
int getTop(StackNode * stack){
if(!stack -> next) return 0;
return stack -> next -> data;
}
/*显示栈的元素个数,由自己实现!*/
int getStackLen(StackNode * stack){
int stackLen = 0;
while(stack -> next){
stackLen ++;
stack = stack -> next;
}
return stackLen;
}
int main()
{
int topElem = -1;
StackNode * stack = initStack();
push(stack, 100);
push(stack, 200);
push(stack, 300);
push(stack, 400);
printf("本次出栈的元素为:%d\n",pop(stack));
topElem = getTop(stack);
printf("现在栈顶元素为:%d\n",topElem);
printf("现在栈内元素个数为:%d\n",getStackLen(stack));
////////////////////////////////////////////////////////////////
printf("本次出栈的元素为:%d\n",pop(stack));
topElem = getTop(stack);
printf("现在栈顶元素为:%d\n",topElem);
printf("现在栈内元素个数为:%d\n",getStackLen(stack));
/////////////////////////////////////////////////////////////////
printf("本次出栈的元素为:%d\n",pop(stack));
topElem = getTop(stack);
printf("现在栈顶元素为:%d\n",topElem);
printf("现在栈内元素个数为:%d\n",getStackLen(stack));
/////////////////////////////////////////////////////////////////
printf("本次出栈的元素为:%d\n",pop(stack));
topElem = getTop(stack);
printf("现在栈顶元素为:%d\n",topElem);
printf("现在栈内元素个数为:%d\n",getStackLen(stack));
return 0;
}
栈的链式实现(c语言)
最新推荐文章于 2022-03-27 11:27:38 发布