c++栈的又该怎么实现呢?有什么方法实现c++的栈呢?接下来红黑小编就来介绍一下c++栈的简单实现的方法,希望对大家有所帮助。
#include
using namespace std;
struct node
{
int data;
node*next;
};
bool isnempty(node*head)
{
if (head == NULL)
return 0;
else
return 1;
}
void push(node*&head, int data)//压入
{
node*a;
a= new node;
a->data = data;
if (head == NULL)
a->next = NULL;
else
a->next = head;
head = a;
}
void pop(node*head)//弹出
{
while (head)
{
cout << head->data << " ";
head = head->next;
}
}
void top(node*head)//返回栈顶元素
{
cout << head->data;
}
int main()
{
int n;
node*head = NULL;
while (cin >> n)
{
if (n == 0) break;
else
push(head, n);
}
if (isnempty(head))
{
top(head);
cout << endl;
pop(head);
}
}