本文最后更新于:3 个月前
本文主要总结了栈的链式存储方式,包括有无头结点两种情况和相关的完整实现代码。
链栈
有头结点的完整实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| #include<iostream> #include<string>
using namespace std;
typedef struct SNode { int data; struct SNode * next; int top; }SNode,*SqStack;
void InitStack(SqStack& S) { S = new SNode; S->top = -1; S->next = NULL; }
bool StackEmpty(SqStack S) { if (S->top == -1) { return true; } else { return false; } }
bool Push(SqStack& S, int e) { SNode* p = new SNode; p->data = e; p->next = S->next; S->next = p; p->top = ++(S->top);
return true; }
bool Pop(SqStack& S, int& e) { if (S->top == -1) { return false; } e = S->next->data; if (!S->next->next) { S->top--; return true; } S->next = S->next->next; S->top--; return true; }
void GetTop(SqStack S, int& e) { if (S->top == -1) { return; } e = S->next->data; }
int main() { SqStack S; InitStack(S); cout << "栈是否为空:" << StackEmpty(S) << endl; int a = 10; int b;
cout << "入栈:" << Push(S, a) << endl; GetTop(S, b); cout << "读取栈顶元素:" << b << endl; cout << "出栈:" << Pop(S, a) << endl; cout << "栈是否为空:" << StackEmpty(S) << endl; return 0; }
|
无头结点的完整实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| #include<iostream> #include<string>
using namespace std;
typedef struct SNode { int data; struct SNode* next; int top = 0; }SNode, * SqStack;
void InitStack(SqStack& S) { S = NULL; }
bool StackEmpty(SqStack S) { if (S == NULL) { return true; } else { return false; } }
bool Push(SqStack& S, int e) { SNode* p = S; S = new SNode; S->data = e; S->next = p; if (!p) { S->top++; return true; } S->top = p->top+1;
return true; }
bool Pop(SqStack& S, int& e) { if (S == NULL) { return false; } e = S->data; SNode* p = S; S = p->next; return true; }
void GetTop(SqStack S, int& e) { if (S == NULL) { return; } e = S->data; }
int GetSize(SqStack S) { if (S == NULL) { return 0; } return S->top; }
int main() { SqStack S; InitStack(S); cout << "栈是否为空:" << StackEmpty(S) << endl; int a = 10; int b; cout << "栈元素个数:" << GetSize(S) << endl; cout << "入栈:" << Push(S, a) << endl; cout << "栈元素个数:" << GetSize(S) << endl; GetTop(S, b); cout << "读取栈顶元素:" << b << endl; cout << "出栈:" << Pop(S, a) << endl; cout << "栈元素个数:" << GetSize(S) << endl; cout << "栈是否为空:" << StackEmpty(S) << endl; return 0; }
|