1.链表创建成功之后卡了,
2.sclearnlink函数报错说t 是NULL,但是我的if里面不应该已经把l->next == nullptr的情况排除了吗
3.创建链表给他输入值的时候,怎么样写就是按空格分隔数据,怎么样写可以是实现一行一个数据(按行分隔数据)
#include <iostream>
using namespace std;
#define elementype int
#define Maxsize 20
//链式栈
typedef struct sqlink {//链栈定义
elementype data;
sqlink* next;
}*linksq;
//获取栈的元素个数
int slength(const linksq& s) {
return s->data;
}
//遍历栈元素输出
void sqnum(linksq& s) {
int m = slength(s);
cout << "从栈顶向下数据依次为" << endl;
for (int i = 0; i < m; i++) {
cout << s->next->data << " ";
}
}
//链栈的初始化
bool initsqlink(linksq&l) {
l = new sqlink;
l->next = nullptr;
l->data = 0; //将元素个数放在top上面指针的data 域里
return true;
}
//判断栈是否为空
bool sisemptye(linksq&l) {
if (l->next == nullptr) {
return true;
}
else return false;
}
//压栈
void spush(linksq& s, const elementype& e) {
sqlink* t = new sqlink;
t->data = e;
t->next = s->next;
s->next = t;
}
//弹栈
void spop(linksq& s, elementype& e) {
sqlink* p = s->next;
e = p->data;
s->next = p->next;
(s->data)--;
delete p;
}
//创建栈
bool creatsq(linksq& s) {
cout << "请输入元素个数" << endl;
cin >> s->data;
elementype input;
cout << "请输入栈的元素" << endl;
for (int i = 0; i < s->data; i++) {
cin >> input;
spush(s, input);
return true;
}
/* for (int i = 0; i < s->data; i++) {
sqlink* p = new sqlink;
cin >> p->data;
p->next = s->next;
}*/
}
//清空栈
bool sclearnlink(linksq& l) {
if (l->next == nullptr) {
cout << "链表为空" << endl;
return false;
}
linksq t = l->next;
linksq p = t;
while (p) {
p = t;
t = t->next;
delete p;
}
l->data = 0;
l->next = nullptr;
return 0;
}
//销毁栈
bool destorysq(linksq& l) {
if (l == nullptr) {
cout << "链表不存在" << endl;
}
linksq t = l->next, p;
while (t) {
p = t;
t = t->next;
delete p;
}
return true;
}
int main()
{
//链栈
linksq n = new sqlink;
if (initsqlink(n))
{
cout << "链式栈初始化成功" << endl;
if (creatsq(n)) {
cout << "链表创建成功!" << endl;
}
else cout << "链表初始化失败!" << endl;
}
sqnum(n);
elementype q;
cout << "请输入要入栈的元素" << endl;
cin >> q;
spush(n, q);
elementype f;
spop(n, f);
cout << "弹出元素为" << f<<endl;
int w;
cout << "清空栈则输入1,不清空则输入0" << endl;
cin >> w;
if (w) {
if (sclearnlink(n))cout << "清空成功" << endl;
else cout << "清空失败" << endl;
}
}