线性结构
学习内容包括堆栈的顺序存储和链式存储
顺序存储
用列表实现,创建一个结构体。Last表示当前位置。
#include <iostream>
using namespace std;
typedef int Position;
struct LNode
{
int Data[10];
Position Last;
};
void Creat(LNode *L) //初始化
{
L->Last = -1;
}
bool IsEmpty(LNode *L)
{
if (L->Last == -1)
return true;
else
return false;
}
bool IsFull(LNode *L)
{
if (L->Last == 9)
return true;
else
return false;
}
bool Push(LNode *L, int num)
{
if (IsFull(L)) {
cout << "Full!" << endl;
return false;
}
else
{
L->Last++;
int p = L->Last;
L->Data[p] = num;
return true;
}
}
int Pop(LNode *L)
{
if (IsEmpty(L))
{
cout << "None!" << endl;
}
else
{
return (L->Data[(L->Last)--]);
}
}
int main()
{
LNode *L;
L = new LNode;
Creat(L);
for (int i = 0; i < 5; i++)
{
int num;
cout << "Enter Number:";
cin >> num;
Push(L, num);
}
for (int i = 0; i < 5; i++)
{
int num;
num = Pop(L);
cout << "Number:" << num << endl;
}
return 0;
}
链式存储
用链表实现。链表使用需要注意添加和删除节点的步骤顺序。
#include <iostream>
using namespace std;
struct ListNode {
int data;
ListNode *next;
};
void CreatStack(ListNode *s) //初始化
{
s->next = NULL;
}
bool IsEmpty(ListNode *s) //判断是否为空,空为true
{
if (s->next != NULL)
return false;
else
return true;
}
void Push(ListNode *s, int x) //插入元素
{
ListNode *p;
p = new ListNode;
p->data = x;
p->next = s->next;
s->next = p;
}
int Pop(ListNode *s, int &e) //出栈
{
ListNode *p;
if (IsEmpty(s))
return 0;
else
{
p = s->next;
e = p->data;
s->next = p->next;
delete p;
}
}
void Destroy(ListNode *s)
{
ListNode *p;
while (!IsEmpty(s))
{
p = s->next;
s->next = p->next;
delete p;
}
}
int main()
{
ListNode *s;
s = new ListNode;
CreatStack(s);
int num;
if (IsEmpty(s))
cout << "Empty!" << endl;
else
cout << "Not Empty!";
for (int i = 0; i < 7; i++)
{
cout << "Enter number:";
cin >> num;
Push(s, num);
}
for (int i = 0; i < 3; i++)
{
Pop(s, num);
cout << "data:" << num << endl;
}
if (IsEmpty(s))
cout << "Empty!";
else
cout << "Not Empty!";
Destroy(s);
return 0;
}