标签:
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <stdbool.h> //节点元素 typedef struct NODE{ int data; struct NODE *pNext; }NODE,*PNODE; //栈结构 typedef struct STACK{ PNODE sTop; PNODE sBottom; int stack_size; }STACK,*PSTACK; void initStack(PSTACK pS); void push(PSTACK pS,int data); bool isEmpty(PSTACK pS); int pop(PSTACK pS); int length(PSTACK pS); int getTop(PSTACK pS); void clear(PSTACK pS); void traverse(PSTACK pS); int main(int argc, char *argv[]) { STACK S; initStack(&S); push(&S,2); traverse(&S); return 0; } //销毁栈 //void destroy(PSTACK pS){ //} //遍历 void traverse(PSTACK pS){ PNODE pNew = pS->sTop; while(pNew != pS->sBottom){ printf("%d",pNew->data); pNew = pNew->pNext; } return; } //清空栈(递归) void clear(PSTACK pS){ if(isEmpty(pS)){ printf("栈已清空!"); return; }else{ PNODE pNew = pS->sTop; pS->sTop = pS->sTop->pNext; free(pNew); pS->stack_size--; clear(pS); } } //获取栈顶元素 int getTop(PSTACK pS){ if(isEmpty(pS)){ printf("栈为空!"); exit(-1); }else{ return pS->sTop->data; } } //长度 int length(PSTACK pS){ return pS->stack_size; } //判空 bool isEmpty(PSTACK pS){ if(pS->sBottom == pS->sTop){ return true; } return false; } //出栈 int pop(PSTACK pS){ if(isEmpty(pS)){ printf("栈为空!"); exit(-1); }else{ PNODE pNew = pS->sTop; pS->sTop = pS->sTop->pNext; int data = pNew->data; free(pNew); (pS->stack_size)--; return data; } } //压栈 void push(PSTACK pS,int data){ PNODE pNew = (PNODE)malloc(sizeof(NODE)); pNew->pNext =pS->sTop; pNew->data = data; pS->sTop = pNew; (pS->stack_size)++; return; } //初始化栈空间 void initStack(PSTACK pS){ pS->sTop = (PNODE)malloc(sizeof(NODE)); if(pS->sTop == NULL){ printf("初始化失败!可能是内存分配失败"); }else{ pS->sBottom = pS->sTop; pS->sBottom->pNext = NULL; pS->stack_size = 0; } return; }
用malloc函数申请内存,需要一个申请一个,还有销毁栈没实现,看网上的代码怎么感觉怪怪的,请大神指点!!
标签:
原文地址:http://my.oschina.net/icngor/blog/479101