链栈,8进制转换

链栈

  • 什么是链栈?
    • 首先定义结构体
      • 初始化
      • 入栈
      • 出栈
      • 判断栈是否为空
    • 代码演示

什么是链栈?

链栈是指采用链式存储结构实现的栈

首先定义结构体

typedef struct StackNode{
int data;
struct StackNode * next;
}StackNode,*LinkStack;

初始化

int InitStack(LinkStack &S)
{
S = NULL;
return 1;
}

入栈

int Push(LinkStack &S,int e)
{
LinkStack p;
p = (LinkStack)malloc(sizeof(StackNode));
p->data = e;
p->next = S;
S = p;
return 1;
}

出栈

int Pop(LinkStack &S,int &e)
{
LinkStack p;
if(S == NULL) return 0;
e = S->data;
p = S; S = S->next;
free§;
return 1;
}

判断栈是否为空

int StackEmpty(LinkStack &S)
{
if(S == NULL) return 1;
else return 0;
}

代码演示

#ifndef STACK_H_INCLUDED  //栈头
#define STACK_H_INCLUDED
typedef struct StackNode{
    int data;
    struct StackNode * next;
}StackNode,*LinkStack;
int InitStack(LinkStack &S);
int Push(LinkStack &S,int e);
int Pop(LinkStack &S,int &e);
int StackEmpty(LinkStack &S);
#endif // STACK_H_INCLUDED


#include "stack.h"  //栈文件
#include 
int InitStack(LinkStack &S)
{
    S = NULL;
    return 1;
}

int Push(LinkStack &S,int e)
{
    LinkStack p;
    p = (LinkStack)malloc(sizeof(StackNode));
    p->data = e;
    p->next = S;
    S = p;
    return 1;
}

int Pop(LinkStack &S,int &e)
{
    LinkStack p;
    if(S == NULL) return 0;
    e = S->data;
    p = S; S = S->next;
    free(p);
    return 1;
}
int StackEmpty(LinkStack &S)
{
    if(S == NULL) return 1;
    else return 0;
}


#include    //main函数
#include "stack.h"
using namespace std;
void conversion();
int main()
{
   conversion();   //8进制转换程序
}
void conversion()
{
    LinkStack S;
    int e;
    int N ;
    InitStack(S);
    std::cout << "请输入一个十位数数字:";
    cin>>N;
    while(N)
    {
        Push(S, N%8);
        N/=8;
    }
    std::cout <<"转换为8进制后的数字是:";
    while(!StackEmpty(S))
    {
        Pop(S,e);
        std::cout << e;
    }
}

你可能感兴趣的:(数据结构,链栈,进制转换)