链栈的基本操作实现

1. 链栈含头结点模型示意图如下:

1334974-20180705161847867-987587466.png

2. 链栈结构定义如下:

struct StackNode {
    int data;
    StackNode* next;
};

3. 链栈的基本操作函数如下:

  • StackNode* createStack(); // 创建栈头结点
  • void Push(StackNode* head, int item); // 入栈
  • int Pop(StackNode* head); // 出栈,并返回出栈数据
  • int getStackLength(StackNode* head); // 获取栈元素个数

4. 具体代码实现如下:

#include <iostream>

using namespace std;

// 结点结构
struct StackNode {
    int data;
    StackNode* next;
};

// 创建栈头结点
StackNode* createStack() {
    StackNode* head = (StackNode*)malloc(sizeof(StackNode));
    if (head == NULL) {
        cout << "Memory allocate failed." << endl;
        return NULL;
    }
    head->data = 0;
    head->next = NULL;
    return head;
}

// 入栈
void Push(StackNode* head, int item) {
    if (head == NULL) {
        return;
    }
    StackNode* node = (StackNode*)malloc(sizeof(StackNode));
    if (node == NULL) {
        cout << "Memory allocate failed." << endl;
        return;
    }
    node->data = item;
    node->next = head->next;
    head->next = node;
}

// 出栈
int Pop(StackNode* head) {
    if (head == NULL || head->next == NULL) {
        cout << "Error." << endl;
        return 0;
    }
    StackNode* node = (StackNode*)malloc(sizeof(StackNode));
    if (node == NULL) {
        cout << "Memory allocate failed." << endl;
        return 0;
    }
    StackNode* temp = head->next;
    head->next = temp->next;
    int val = temp->data;
    free(temp);
    return val;
}

// 获取栈元素个数
int getStackLength(StackNode* head) {
    if (head == NULL || head->next == NULL) {
        return 0;
    }
    StackNode* p = head->next;
    int len = 0;
    while (p != NULL) {
        len++;
        p = p->next;
    }
    return len;
}

int main() {
    StackNode* head = NULL;
    head = createStack();
    Push(head, 5);
    Push(head, 4);
    Push(head, 3);
    cout << getStackLength(head) << endl;
    cout << Pop(head) << endl;
    cout << Pop(head) << endl;
    cout << getStackLength(head) << endl;
    cout << Pop(head) << endl;
    cout << getStackLength(head) << endl;
    system("pause");
    return 0;
}

5. 运行结果截图如下:

1334974-20180705162221637-1757187620.png

转载于:https://www.cnblogs.com/yiluyisha/p/9268415.html

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值