c++实现链栈

来源:互联网 发布:免手机号注册qq 知乎 编辑:程序博客网 时间:2024/06/11 21:19
// test.cpp : 定义控制台应用程序的入口点。IDE是vs2013//#include "stdafx.h"#include<iostream>using namespace std;typedef struct node{int data;struct node *next;}nodes, *linkstack;//nodes表示结点,linkstack表示栈指针void InitalStack(linkstack &top)//1.初始化链栈InitalStack(栈名){top = NULL;}void Push(linkstack &top, int x)//2.进栈Push(元素值){nodes *p;//创建新结点的指针p = new nodes;//指针初始化,指向一个新结点p->data = x;//赋值p->next = top;top = p;//新结点成为栈顶结点}int Pop(linkstack &top)//3.出栈运算{nodes *p;//创建新结点的指针p = new nodes;//指针初始化,指向一个新结点int x;//用x返回被出栈的元素值if (top == NULL){return 0;}else//当栈不为空{p = top;//取栈顶元素x = p->data;top = p->next;//栈顶下移delete p;//删除栈顶元素return x;//返回其值}}int GetTop(linkstack &top)//4.取栈顶元素{int x;if (top == NULL){return 0;}else//当栈不为空{x = top->data;//取栈顶结点的值return x;//返回值}}int IsEmpty(linkstack &top)//5.判断栈是否为空{if (top == NULL)//空栈{return 1;}else//非空栈{return 0;}}int _tmain(int argc, _TCHAR* argv[]){linkstack t;//创建一个指向结点的栈指针InitalStack(t);//初始化栈Push(t, 9);//进栈Push(t, 8);cout << Pop(t)<<endl;//出栈cout << GetTop(t);//取栈顶元素system("pause");return 0;
<span style="font-family: Arial, Helvetica, sans-serif;">}</span>
0 0
原创粉丝点击