在写链栈的时候 和 顺序栈一样 犯了两个错误: 一个是 在 入栈 和 进栈顶时候 忘记 操作 linkstack.len 了,另一个是 在写 stackClear 的时候 犯了一个 低级的内存错误。
这两个问题 都是 粗心造成的。
希望 引以为戒
在做下一个例子:数值转换时,又发现了一个问题:在 stackPop 没有返回 pop元素的值。唉 
欢迎指出代码不足
下面上代码:
// LinkStack.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
typedef int elelmentType;
enum E_State
{
E_State_Error = 0,
E_State_Ok = 1,
};
//链表节点node
struct 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->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;
//找到栈顶元素的前驱
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;
}
原文地址:http://blog.csdn.net/fuming0210sc/article/details/44017343