思路:链表实现栈比较自然,而且这里使用了双链表,单链表也够用。链表实现的栈个人感觉就是灵活性强一点,复杂度方面不如数组实现。
代码:
// linkedliststack.cpp : 定义控制台应用程序的入口点。
// 链表实现栈
#include "stdafx.h"
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::cerr;
//点结构
typedef struct Node {
int data;
Node *prev; //指向前驱结点
Node *next; //指向后继结点
};
//链表结构
typedef struct Linkedlist {
Node *head;
};
//插入结点
void push(Linkedlist &L, Node *x)
{
x->next = L.head;
if (L.head != nullptr)
L.head->prev = x;
L.head = x;
x->prev = nullptr;
}
//删除头结点
int pop(Linkedlist &L)
{
if (L.head == nullptr)
{
cerr << "stack underflow!" << endl;
return -1;
}
else
{
int temp = L.head->data;
if (L.head->next != nullptr)
L.head = L.head->next;
else
L.head = nullptr;
return temp;
}
}
void traverse(Linkedlist L)
{
cout << "current stack:";
Node *x = L.head;
while (x)
{
cout << x->data << " ";
x = x->next;
}
cout << endl;
}
int main()
{
int temp;
Linkedlist L;
L.head = nullptr;
Node *x;
int cmd;
while (cin>>cmd)
{
switch (cmd)
{
case 1:
cin >> temp;
x = new Node;
x->data = temp;
push(L, x);
traverse(L);
x = nullptr;
break;
case 2:
cout << pop(L) << endl;
traverse(L);
break;
default:
cerr << "error command!" << endl;
break;
}
}
system("pause");
return 0;
}
运行结果: