栈的创建、入栈、出栈、统计长度

来源:互联网 发布:网络电视机顶盒系统 编辑:程序博客网 时间:2024/06/06 17:29

C++实现,采用链表存储,因为顺序存储较为简单,不再重复叙述。

#include <iostream>using namespace std;struct node         //栈的节点{    int data;    struct node *next;};struct linkStack{    struct node *top;      //指向栈顶节点    int lengthStack;      //栈长度};//创建一个空栈void create(struct linkStack *S){    S->top = NULL;    S->lengthStack = 0;}//入栈数据numvoid stackInsert(struct linkStack *S, int num){    struct node *p = new node;    p->data = num;    if(S->top == NULL)      //当栈为空时        S->top = p;    else        //当栈不为空时    {        p->next = S->top;        S->top = p;    }    S->lengthStack++;}//出栈并打印出栈的数据void stackPop(struct linkStack *S){    struct node *temp;    if(S->top != NULL)    {        temp = S->top;        S->top = S->top->next;        cout<<temp->data<<endl;        delete(temp);        S->lengthStack--;    }}int main(){    linkStack S;    create(&S);    /********入栈*************/    stackInsert(&S, 1);    stackInsert(&S, 2);    stackInsert(&S, 3);    stackInsert(&S, 4);    /********出栈*************/    stackPop(&S);    stackPop(&S);    stackPop(&S);    stackPop(&S);    return 0;}
0 0
原创粉丝点击