看数据结构写代码(12)栈的应用(三) 行编辑器

所写范例为 看 严蔚敏《数据结构-c语言版》 3.2.3 小节 《行编辑程序》时,, 写的 读书 代码

下面直接上代码:

// LinkStack.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <stdlib.h>typedef char 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;while (next != NULL){printf("%c",next->data);next = next->next;}}//括号匹配#include <cstring>int _tmain(int argc, _TCHAR* argv[]){linkStack stack;stackInit(&stack);while (true){//错误 char * s = "sdfdfsdfssdfsd";char s[50];printf("请输入表达式:");scanf("%s",s);if (strcmp(s,"exit") == 0){break;}printf("表达式为:%s\n",s);char * p = s;while (*p != '\0'){char data = *p;if (data == '#'){char pop;stackPop(&stack,&pop);}else if(data == '@'){stackClear(&stack);}else{stackPush(&stack,data);}p++;}printf("处理后:");stackTraverse(stack);//清空栈printf("\n\n");stackClear(&stack);}//释放内存stackDestory(&stack);return 0;}

夫妇一条心,泥土变黄金。

看数据结构写代码(12)栈的应用(三) 行编辑器

相关文章:

你感兴趣的文章:

标签云: