链头 == 栈顶。
cpp
#include<iostream>
using namespace std;
// 链栈
typedef int ElemType;
typedef struct Linknode {
ElemType data;
struct Linknode *next;
} *LiStack;
// 初始化
void InitLiStack(LiStack &S) {
S = (LiStack)malloc(sizeof(struct Linknode));
S->next = NULL;
}
// 入栈
bool PushLiStack(LiStack &S, ElemType x) {
LiStack p = (LiStack)malloc(sizeof(struct Linknode));
p->data = x;
p->next = S->next;
S->next = p;
return true;
}
// 出栈
bool PopLiStack(LiStack &S, ElemType &x) {
if (S->next == NULL) return false;
LiStack p = S->next;
x = p->data;
S->next = p->next;
free(p);
return true;
}
// 遍历
void TraverseLiStack(LiStack S) {
LiStack p = S->next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
// 求链栈长度
int StackLength(LiStack S) {
int length = 0;
LiStack p = S->next;
while (p != NULL) {
length++;
p = p->next;
}
return length;
}
int main() {
LiStack S;
ElemType x;
InitLiStack(S);
PushLiStack(S, 1);
PushLiStack(S, 2);
PushLiStack(S, 3);
PopLiStack(S, x);
cout << "出栈元素:" << x << endl;
TraverseLiStack(S);
cout << "链栈长度:" << StackLength(S) << endl;
return 0;
}