链栈的算法实现
特别要注意入栈和出栈的操作,虽然是链栈,但是本质上还是栈,不能违反栈的特性,后进先出,不能随便的删除元素,只能栈顶删除
#include<stdlib.h>
#include<iostream>
using namespace std;
typedef int Elemtype;
typedef struct _LinkStack {
Elemtype date;//数据域
_LinkStack* next;//指针域
}LinkStack,LinkNode;
//初始化链栈
bool InitLinkStack(LinkStack*& S) {
S = new LinkStack;
S->next = NULL;
S->date = -1;
return true;
}
//入栈
bool insert(LinkStack*& S, LinkNode* node) {
if (!S)
return false;
LinkNode* p = S;
while (p->next) {
p = p->next;
}
node->next = NULL;
p->next = node;
return true;
}
//获取栈顶元素,但是其他不变
Elemtype GetTop(LinkStack*& S) {
if (!S)
return -1;
Elemtype e;
LinkNode *p=NULL;
p = new LinkNode;
p = S;
while (p->next) {
p = p->next;
}
e = p->date;
return e;
}
//出栈
bool deleteLink(LinkStack*& S) {
if (!S)
return false;
LinkNode* q = S;
LinkNode* p = q;
while (q->next)
{
p = q;
q = q->next;
}
p->next = NULL;
delete q;
return true;
}
//打印栈元素
void printf(LinkStack*& S) {
LinkNode* p;
p = S->next;
while (p) {
cout << p->date << " ";
p = p->next;
}
cout << endl;
}
int main(void) {
LinkStack* S;//头节点
LinkNode* p;
InitLinkStack(S);
//入栈
p = new LinkNode;
int n = 0;
cout << "请输入想要输入的元素个数n:";
cin >> n;
cout << "请依此输入各个元素" << endl;
while (n--) {
cin >> p->date;
insert(S, p);
}
printf(S);
cout << endl;
//获取栈顶元素
cout << "栈顶元素是:" << GetTop(S);
cout << endl;
if (deleteLink(S)) {
cout << "出栈成功" << endl;
return true;
}
else {
cout << "出栈失败" << endl;
return false;
}
printf(S);
system("pause");
return 0;
}
链栈说到底还是栈,只能从栈顶删除和插入元素