链式栈的初始化,判空,进栈,出栈,求长,求顶,打印,清空和销毁

来源:互联网 发布:javascript基础 编辑:程序博客网 时间:2024/04/30 10:43
链接地址http://blog.csdn.net/stpeace/article/details/8112821#include<iostream>using namespace std;typedef struct LNode{          int data;//数据域          struct LNode *next;//指针域}LNode,*Stack;//LNode 定义一个节点,Stack定义的是一个指向节点的地址void initStack(LNode *&lst){         lst=new LNode;         lst->next=NULL;}int isEmpty(LNode *lst)//不是空返回0,是空返回1{      if(lst->next==NULL)//判断栈的第一个节点是否为NULL             return 1;      else             return 0;      return 0;}void Push(LNode *lst,int x)//进栈{      LNode *p;      p=new LNode;      p->next=NULL;//为新建节点的指针域设置一下,不要也可以,设置了可以避免一些错误      //头插法       p->data=x;       p->next=lst->next;//处理p的指针域       p->next=NULL;//处理lst的指针域}int Pop(LNode *lst)//出栈{       LNode *p;       if(lst->next==NULL)       {            return 0;       }       p=lst->next;//用p做中间处理       lst->next=p->next;       delete p;       return 1;}int getLength(LNode *lst)//求长{       LNode *p=lst;       int length=0;       while(NULL!=p->next)       {            p=p->next;            length++;        }          return length;}int getTop(LNode *lst)//访问栈的第一个数据{     if(isEmpty(lst))             exit(1);//退出      return lst->next->data;}void clear(LNode *lst)//清空{       /*while(lst->next!=NULL)          {                  Pop(lst);           }*/          while(!isEmpty(lst))//isEmpty不是空返回0,是空返回1.0相当于false,!false相当于true          {                Pop(lst);          }         }void destory(LNode *lst){      while(!isEmpty(lst))            Pop(lst);       delete lst;//只是销毁指针指向的数据,而指针本身并未销毁       lst=NULL;}void print(LNode *lst){      LNode *p;      while(lst->next!=NULL)      {              p=lst->next;              cout<<p->data<<endl;              lst->next=p->next;      }}int main(){         Stack stack1;         initStack(stack1);         isEmpty(stack1);         Push(stack1);         Push(stack1);         Pop(stack1);         print(stack1);         int b;         b=getLength(stack1);         cout<<b<<endl;                  clear(stack1);         destory(stack1);          return 0;}

1 0
原创粉丝点击