C++实现链栈(未用模板类)
整体代码
#include <iostream>
using namespace std;
class LNode
{
public:
int data; //数据域
LNode* next; //指针域
};
class Method
{
public:
LNode *lnd;
int LNode_size;
void InitLNode(); //初始化
void LNodeisEmpty(); //判空
void PrintLNode(); //打印
void PushLNode(); //入栈
int PopLNode(); //出栈
};
void Method::InitLNode()
{
lnd = new LNode;
lnd->next = NULL;
LNode_size = 0;
}
void Method::LNodeisEmpty()
{
if (lnd->next == NULL)
{
cout << "链栈为空" << endl;
}
else
{
cout << "不为空" << endl;
}
}
void Method::PrintLNode()
{
if (lnd->next == NULL)
{
cout << "链栈为空" << endl;
return;
}
LNode* p = new LNode;
p = lnd->next;
int i = LNode_size;
while (i != 0)
{
cout << p->data <<endl;
p = p->next;
i--;
}
}
void Method::PushLNode()
{
//相当于单链表的头插,在头部插入,当做栈顶,尾部当做栈尾
//对应而言,出栈就是头删
int x, n;
while (true)
{
cout << "请输入要插入多少个数据:";
cin >> n;
if (n <= 0)
{
cout << "输入有误,重新输入" <<endl;
continue;
}
break;
}
for (int i = 0; i < n; i++)
{
cout << "请输入数据第" << i+1 << "个数据:";
cin >> x;
LNode* p = new LNode;
p->next = NULL;
p->data = x;
p->next = lnd->next;
lnd->next = p;
}
LNode_size = LNode_size + n;
}
int Method::PopLNode()
{
if (lnd->next == NULL)
{
cout << "出栈失败,链栈为空" << endl;
return -1;
}
LNode* p = lnd->next;
lnd->next = p->next;
free(p);
LNode_size--;
}
int main()
{
LNode lnd;
Method md;
md.InitLNode();
md.LNodeisEmpty();
md.PopLNode();
md.PushLNode();
md.PrintLNode();
md.PopLNode();
md.PrintLNode();
return 0;
}
分块代码
链栈的类定义
class LNode
{
public:
int data; //数据域
LNode* next; //指针域
};
方法类定义
class Method
{
public:
LNode *lnd;
int LNode_size;
void InitLNode(); //初始化
void LNodeisEmpty(); //判空
void PrintLNode(); //打印
void PushLNode(); //入栈
int PopLNode(); //出栈`在这里插入代码片`
};
初始化
void Method::InitLNode()
{
lnd = new LNode;
lnd->next = NULL;
LNode_size = 0;
}
判空
void Method::LNodeisEmpty()
{
if (lnd->next == NULL)
{
cout << "链栈为空" << endl;
}
else
{
cout << "不为空" << endl;
}
}
ps:这里可以使用LNode_size == 0 来判空
打印
void Method::PrintLNode()
{
if (lnd->next == NULL)
{
cout << "链栈为空" << endl;
return;
}
LNode* p = new LNode;
p = lnd->next;
int i = LNode_size;
while (i != 0)
{
cout << p->data <<endl;
p = p->next;
i--;
}
}
入栈(类似于单链表头插)
void Method::PushLNode()
{
//相当于单链表的头插,在头部插入,当做栈顶,尾部当做栈尾
//对应而言,出栈就是头删
int x, n;
while (true)
{
cout << "请输入要插入多少个数据:";
cin >> n;
if (n <= 0)
{
cout << "输入有误,重新输入" <<endl;
continue;
}
break;
}
for (int i = 0; i < n; i++)
{
cout << "请输入数据第" << i+1 << "个数据:";
cin >> x;
LNode* p = new LNode;
p->next = NULL;
p->data = x;
p->next = lnd->next;
lnd->next = p;
}
LNode_size = LNode_size + n;
}
出栈(相当于单链表的头删)
int Method::PopLNode()
{
if (lnd->next == NULL)
{
cout << "出栈失败,链栈为空" << endl;
return -1;
}
LNode* p = lnd->next;
lnd->next = p->next;
free(p);
LNode_size--;
}
如有错误欢迎指正,谢谢!!!