看数据结构写代码(9)链栈的实现

在写链栈的时候 和 顺序栈一样 犯了两个错误: 一个是 在 入栈 和 进栈顶时候 忘记 操作 linkstack.len 了,另一个是 在写 stackClear 的时候 犯了一个 低级的内存错误。

这两个问题 都是 粗心造成的。

希望 引以为戒

在做下一个例子 :《进制转换》时,,又发现了一个问题:在 stackPop 没有返回 pop元素的值。唉

在做下下一个例子:《括号匹配》时,又发现了一个问题:在stackClear没有将 头指针后继设置为NULL: 代码为: (stack->bottom->next = NULL;)

欢迎指出代码不足

下面上代码:

// LinkStack.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <stdlib.h>typedef int elelmentType;enum E_State{E_State_Error = 0,E_State_Ok = 1,};//链表节点nodestruct lStackNode{elelmentType data;lStackNode * next;};//链栈struct linkStack{lStackNode * bottom;lStackNode * top;int len;};lStackNode * makeNode(elelmentType data){lStackNode * pNode = (lStackNode *)malloc(sizeof(lStackNode));if (pNode != NULL){pNode->data = data;pNode->next = NULL;}return pNode;}E_State stackInit(linkStack * lStack){//分配头节点lStackNode * pNode = (lStackNode *) malloc(sizeof(lStackNode));if (pNode == NULL){return E_State_Error;}pNode->next = NULL;//栈顶和栈底指向同一个节点时为空.lStack->bottom = lStack->top = pNode;lStack->len = 0;return E_State_Ok;}void stackClear(linkStack * stack){lStackNode * next = stack->bottom->next;while (next != NULL){lStackNode * freeNode = next;/*又粗心了。。。free(freeNode);next = next->next;*/next = next->next;free(freeNode);}stack->top = stack->bottom;//修复错误stack->bottom->next = NULL;stack->len = 0;}void stackDestory(linkStack * stack){stackClear(stack);free(stack->top);stack->top = stack->bottom = NULL;}E_State stackGetTop(linkStack stack,elelmentType * topData){//链表的栈顶 指向 栈顶元素if (stack.top != stack.bottom){*topData = stack.top->data;return E_State_Ok;}else{return E_State_Error;}}int stackLen(linkStack stack){return stack.len;}bool stackEmpty(linkStack stack){return stack.top == stack.bottom ? true : false;}E_State stackPush(linkStack * stack,elelmentType data){lStackNode * node = makeNode(data);if (node != NULL){stack->top->next = node;stack->top = node;stack->len++;}else{return E_State_Error;}}E_State stackPop(linkStack * stack,elelmentType * data){if (stack->top != stack->bottom){//首先指向第一个元素.lStackNode * next = stack->bottom;//修复错误。。忘记写了*data = stack->top->data;//找到栈顶元素的前驱while (next->next != stack->top){next = next->next;}free(stack->top);next->next = NULL;stack->top = next;//忘记加了stack->len–;return E_State_Ok;}else{return E_State_Error;}}//从栈底到 栈顶的 遍历void stackTraverse(linkStack stack){//首先指向第一个元素lStackNode * next = stack.bottom->next;printf("————遍历开始———-\n");while (next != NULL){printf("———–%d———-\n",next->data);next = next->next;}printf("————遍历结束———-\n");}int _tmain(int argc, _TCHAR* argv[]){linkStack stack;stackInit(&stack);for (int i = 1; i < 13; i++){stackPush(&stack,i);}elelmentType top;stackPop(&stack,&top);stackPop(&stack,&top);stackTraverse(stack);stackGetTop(stack,&top);char * s = stackEmpty(stack) ? "true" : "false";printf("栈长 :%d,栈顶元素为 :%d,栈是否为空:%s",stackLen(stack),top,s);stackDestory(&stack);return 0;}

抱最大的希望,为最大的努力,做最坏的打算

看数据结构写代码(9)链栈的实现

相关文章:

你感兴趣的文章:

标签云: