链栈的操作,附一个行编辑器程序。

来源:互联网 发布:古剑奇谭二电视剧知乎 编辑:程序博客网 时间:2024/06/03 23:44

链式栈的各种操作。最后的两个函数为,行编辑器所用到的函数,其中exchange函数的功能是将栈中的元素倒置,这样才有利于输出。

#include<stdio.h>#include<stdlib.h>#include<malloc.h>//各种定义,才与教材的类型符合。typedef int Status;typedef char elemtype;#define OK 1#define ERROR -1//数据的存储结构的定义。typedef struct node{elemtype data;struct node *next;}linkstack;//各种函数的声明。linkstack * Init_stack(void);Status Push(linkstack *top,elemtype x);bool Stack_Empty(linkstack *s);Status print_stack(linkstack *s);Status Pop(linkstack *top,elemtype &e);Status DestroyStack(linkstack *top);Status Edit(void);linkstack * exchange(linkstack *top);int main(){Edit();return 0;}//栈的初始化,带有头结点,不带有头结点的链式栈太难写了,也难操作。linkstack * Init_stack(void){linkstack *top;top=(linkstack *)malloc(sizeof(linkstack) );top->data=-1;top->next=NULL;return top;}//入栈Status Push(linkstack *top,elemtype x){linkstack * newnode,*temp;newnode=(linkstack *)malloc(sizeof(linkstack) );newnode->data=x;newnode->next=top->next;top->next=newnode;return OK;}//出栈Status Pop(linkstack *top,elemtype &e){e=top->next->data;linkstack * temp;temp=top->next;top->next=temp->next;free(temp);return OK;}//输出栈的元素Status print_stack(linkstack *s){for(linkstack *p=s;Stack_Empty(p)==false;p=p->next)printf("%c",p->next->data);printf("\n");return OK;}//判断栈是否为空bool Stack_Empty(linkstack *top){if(top->next==NULL)return true;elsereturn false;}//销毁栈的函数Status DestroyStack(linkstack *top){elemtype temp;while(top->next!=NULL)Pop(top,temp);return OK;}/*行编辑器的函数,此函数完成调用各种函数的功能。包括栈的初始化,入栈和出栈等功能,main函数就只用来调用次函数就好了,所以我的main函数就只有句语句啦!*/Status Edit(void){elemtype ch;linkstack *top;top=Init_stack();ch=getchar();while(ch!=EOF&&ch!='\n'){switch(ch){case '#':Pop(top,ch);break;case '@':DestroyStack(top);break;default:Push(top,ch);}ch=getchar();}//print_stack(top);top=exchange(top);print_stack(top);return OK;}//此算法功能是将栈倒置。例如栈中元素1234567倒置成7654321.linkstack * exchange(linkstack *top){linkstack * stack_A;stack_A=Init_stack();elemtype temp;while(Stack_Empty(top)==false){Pop(top,temp);Push(stack_A,temp);}return stack_A;}


原创粉丝点击