• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
七喜不加冰
努力努力再努力
博客园    首页    新随笔    联系   管理    订阅  订阅
堆栈总结

1. 堆栈是一种只允许在表的一段进行插入操作和删除操作的线性表。 其中允许操作的一端是栈顶,栈顶元素的位置由栈顶指针的变量确定。表中没有元素的时候,称为空栈。--“先进后出”顺序

 

2.堆栈的存储结构有 一维数组 和 单向链表 两种方式

2.1 数组实现

 

 

主要操作: PUSH\POP\EMPTY,代码中用

类实现。

// test.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdlib.h"
#include"stack.h"

stack czstack;

int main()
{
    czstack.push('1');
    czstack.push('2');
    czstack.push('3');
    czstack.pop();
    czstack.pop();
    return 0;
}
#pragma once
#define M 100
class stack
{
public:
    char stacksz[M];
    int top;
    int push(char yuansu);
    char pop();
    int empty();
    stack();
    ~stack();
};
#include "stdafx.h"
#include "stack.h"


stack::stack()
{
    top = -1;
}

int stack::push(char yuansu)
{
    if (top == M)
    {
        printf("FULL");
        return 0;
    }
    else
    {
        top++;
        stacksz[top] = yuansu;
        return 1;
    }
}
char stack::pop()
{
    if (top == -1)
        printf("EMPTY");
    else
    {
        top--;
        return stacksz[top];
        
    }
}
int stack::empty()
{
    return -1 == top;
}
stack::~stack()
{
}

2.2 链表实现

   堆栈的链表实现就是用单向链表实现的堆栈结构,top指针指向最新的那个链结点,前文中在链表的数据结构总结中的createlinklist函数返回的就是头链结点的指针list,即list就是top指针。

// test.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdlib.h"
#include"stdlib.h"
struct node {
    char data;
    struct node * link;
};
struct node * list; //堆栈中list即top指针

void createlinklist(int n)
{
    //scanf_s("%d",&n);
    list = NULL;
    for (int i = 1; i <= n; i++)
    {
        struct node *p = (struct node *)malloc(sizeof(struct node));
        p->data = getchar();
        rewind(stdin);
        p->link = NULL;
        //以下为迭代部分
        p->link = list;
        list = p;
    }
}
void push(char ch)    //push在链表中相当于增加链结点
{
    struct node * p;
    p = (struct node *)malloc(sizeof(struct node));
    p->data = ch;
    p->link = list;
    list = p;
}
char pop()    //pop 相当于在链表中删除链结点
{
    char fanhui;
    if (list != NULL)
    {
        fanhui = list->data;
        list = list->link;
        return fanhui;
    }
    else
        printf("EMPTY");
}
int main()
{
    createlinklist(3);
    push('6');
    pop();
    pop();
    pop();
    pop();
    system("pause");
    return 0;
}

 

posted on 2017-11-30 17:13  七喜不加冰  阅读(352)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3