头歌数据结构栈的应用

利用栈实现整数的十进制转八进制

#include "stack_.h"

// 栈操作实现文件
//


Stack* Stack_Create(int maxlen)
// 创建栈
{
    Stack* stk = (Stack*)malloc(sizeof(Stack));
    stk->data = (T*)malloc(sizeof(T)*maxlen);
    stk->max = maxlen;
    stk->top = -1;
    return stk;
}

void Stack_Free(Stack* stk)
// 释放栈
{
    free(stk->data);
    free(stk);
}

void Stack_MakeEmpty(Stack* stk)
// 置为空栈
{
    stk->top = -1;
}

bool Stack_IsEmpty(Stack* stk)
// 判断栈是否空
{
    return -1 == stk->top;
}

bool Stack_IsFull(Stack* stk)
// 判断栈是否满
{
    return stk->top == stk->max-1;
}

T Stack_Top(Stack* stk)
// 获取当前栈顶元素
{
    return stk->data[stk->top];
}

T Stack_Push(Stack* stk, T e)
// 将元素e压入栈顶
// 返回栈顶点元素
{
    if(Stack_IsFull(stk)) {
        printf("Stack_IsFull(): stack full error when push element to the stack!\n");//将元素推送到堆栈时出现堆栈已满错误
        Stack_Free(stk);
        exit(0);
    }
    else{
        stk->top += 1;
        stk->data[stk->top] = e;
        return Stack_Top(stk);
    }
}

T Stack_Pop(Stack* stk)
// 将栈顶元素出栈
// 返回栈顶元素
{
    if(Stack_IsEmpty(stk)) {
        printf("Stack_IsEmpty(): stack empty error when pop element of the stack top!\n");
        Stack_Free(stk);
        exit(0);
    }
    else{
        T topE = Stack_Top(stk);
        stk->top -= 1;
        return topE;
    }
}

void Stack_Print(Stack* stk)
// 打印栈顶到栈低的元素
{
    if (Stack_IsEmpty(stk)) {
        printf("The stack is empty.\n");
        return;
    }
    
    //printf("The stack contains: ");
    for (int i=stk->top; i>=0; i--) {
        printf("%d", stk->data[i]);
    }
    printf("\n");
    
}

void Decimal_Conversion_Octal(T e)
//  利用stack栈实现整数的十进制转八进制
//  输入参数:十进制整数 e
//  打印e的八进制结果,末尾换行
{
    // 请在这里补充代码,完成本关任务
    /********** Begin *********/
    Stack *a=Stack_Create(32);
    while(e)
    {
        Stack_Push(a,e%8);//将e对8取余后入创建的栈a
        e=e/8;
    }
    while(!Stack_IsEmpty(a))
    {
        e=Stack_Pop(a);
        printf("%d",e);
    }
    
    
    
    /********** End **********/
}

利用栈判断字符串括号是否匹配

#include "stack_.h"

// 栈表操作实现文件
//


Stack* Stack_Create(int maxlen)
// 创建栈
{
    Stack* stk = (Stack*)malloc(sizeof(Stack));
    stk->data = (T*)malloc(sizeof(T)*maxlen);
    stk->max = maxlen;
    stk->top = -1;
    return stk;
}

void Stack_Free(Stack* stk)
// 释放栈
{
    free(stk->data);
    free(stk);
}

void Stack_MakeEmpty(Stack* stk)
// 置为空栈
{
    stk->top = -1;
}

bool Stack_IsEmpty(Stack* stk)
// 判断栈是否空
{
    return -1 == stk->top;
}

bool Stack_IsFull(Stack* stk)
// 判断栈是否满
{
    return stk->top == stk->max-1;
}

T Stack_Top(Stack* stk)
// 获取当前栈顶元素
{
    return stk->data[stk->top];
}

T Stack_Push(Stack* stk, T e)
// 将元素e压入栈顶
// 返回栈顶点元素
{
    if(Stack_IsFull(stk)) {
        printf("Stack_IsFull(): stack full error when push element to the stack!\n");
        Stack_Free(stk);
        exit(0);
    }
    else{
        stk->top += 1;
        stk->data[stk->top] = e;
        return Stack_Top(stk);
    }
}

T Stack_Pop(Stack* stk)
// 将栈顶元素出栈
// 返回栈顶元素
{
    if(Stack_IsEmpty(stk)) {
        printf("Stack_IsEmpty(): stack empty error when pop element of the stack top!\n");
        Stack_Free(stk);
        exit(0);
    }
    else{
        T topE = Stack_Top(stk);
        stk->top -= 1;
        return topE;
    }
}

void Stack_Print(Stack* stk)
// 打印栈顶到栈低的元素
{
    if (Stack_IsEmpty(stk)) {
        printf("The stack is empty.\n");
        return;
    }
    
    //printf("The stack contains: ");
    for (int i=stk->top; i>=0; i--) {
        printf("%d", stk->data[i]);
    }
    printf("\n");
    
}

void Bracket_Match(T* str, int len)
//  利用stack栈判断括号是否匹配
//  输入参数:字符串序列,字符串长度
//  若匹配输出YES,否则输出NO,末尾换行
{
    // 请在这里补充代码,完成本关任务
    /********** Begin *********/

    Stack *zhan=Stack_Create(len);
    int i; char c;
    bool flag=1;
    Stack_IsFull(zhan);
    for(i=0;i<len;++i)
    {
        switch(str[i])
        {
            case'(':
            case'[':
            case'{':Stack_Push(zhan,str[i]);//入栈
            break;
         
            case')':
            case']':
            case'}':Stack_Top(zhan);//获取当前栈的元素
                    c=zhan->data[zhan->top];//赋值给c

                   if((c=='('&&str[i]==')')||(c=='['&&str[i]==']')||(c=='{'&&str[i]=='}')){
                Stack_Pop(zhan);// 将栈顶元素出栈
                   }
                     else{
                         flag=0;
                     }

      }
    }
             if(zhan->top!=-1)//判断栈顶指针是否为空
               flag=0;

               if(flag==1) printf("YES\n");
               else   printf("NO\n");
    
    
    /********** End **********/
}

利用栈判断字符串是否为回文串

#include "stack_.h"

// 栈表操作实现文件
//


Stack* Stack_Create(int maxlen)
// 创建栈
{
    Stack* stk = (Stack*)malloc(sizeof(Stack));
    stk->data = (T*)malloc(sizeof(T)*maxlen);
    stk->max = maxlen;
    stk->top = -1;
    return stk;
}

void Stack_Free(Stack* stk)
// 释放栈
{
    free(stk->data);
    free(stk);
}

void Stack_MakeEmpty(Stack* stk)
// 置为空栈
{
    stk->top = -1;
}

bool Stack_IsEmpty(Stack* stk)
// 判断栈是否空
{
    return -1 == stk->top;
}

bool Stack_IsFull(Stack* stk)
// 判断栈是否满
{
    return stk->top == stk->max-1;
}

T Stack_Top(Stack* stk)
// 获取当前栈顶元素
{
    return stk->data[stk->top];
}

T Stack_Push(Stack* stk, T e)
// 将元素e压入栈顶
// 返回栈顶点元素
{
    if(Stack_IsFull(stk)) {
        printf("Stack_IsFull(): stack full error when push element to the stack!\n");
        Stack_Free(stk);
        exit(0);
    }
    else{
        stk->top += 1;
        stk->data[stk->top] = e;
        return Stack_Top(stk);
    }
}

T Stack_Pop(Stack* stk)
// 将栈顶元素出栈
// 返回栈顶元素
{
    if(Stack_IsEmpty(stk)) {
        printf("Stack_IsEmpty(): stack empty error when pop element of the stack top!\n");
        Stack_Free(stk);
        exit(0);
    }
    else{
        T topE = Stack_Top(stk);
        stk->top -= 1;
        return topE;
    }
}

void Stack_Print(Stack* stk)
// 打印栈顶到栈低的元素
{
    if (Stack_IsEmpty(stk)) {
        printf("The stack is empty.\n");
        return;
    }
    
    //printf("The stack contains: ");
    for (int i=stk->top; i>=0; i--) {
        printf("%d", stk->data[i]);
    }
    printf("\n");
    
}

void Palindrome(T* str, int len)
//  利用stack栈判断字符串是否为回文串
//  输入参数:字符串序列,字符串长度
//  若是回文串输出YES,否则输出NO,末尾换行
{
    // 请在这里补充代码,完成本关任务
    /********** Begin *********/
       if(len==1){printf("YES\n");}
       else 
       {
           Stack *z=Stack_Create(100);
           
           if(len%2!=0)//如果长度为奇数,则进入if语句
           {
               int i;
               for(i=len/2;i<len;i++)
               {
                   str[i]=str[i+1];
               }
               for(i=0;i<len-1;i++)
               {
                   char st;
                   st=Stack_Top(z);//赋值栈顶元素给st
                   if(st==str[i])//是否匹配,匹配后进入if语句
                   {
                       Stack_Pop(z);//返回栈顶元素

                   }
                   else
                   {
                     Stack_Push(z,str[i]);//压入栈
                   }
               }
               if(Stack_IsEmpty(z))//判断是否为空
               {
                     printf("YES\n");
               }
               else
               {
                     printf("NO\n");
               }
           }
           else
           {
            for(int i=0;i<len;i++)
            {
                char st=Stack_Top(z);
                if(st==str[i])
                {
                    Stack_Pop(z);        
                }
                else
                {
                    Stack_Push(z,str[i]);
                }
            }
             if(Stack_IsEmpty(z))//判断是否为空
               {
                     printf("YES\n");
               }
               else
               {
                     printf("NO\n");
               }
            
                  }

               }
              
    /********** End **********/
}

算术表达式求值

#include<stdio.h>
#include<stdlib.h>

#define defaultsize 10
#define increasesize 5

typedef struct
{
    char *base;
    char *top;
    int stacksize;//栈的存储容量 
}OPRTstack;

typedef struct
{
    double *base;
    double *top;
    int stacksize;
}NUMstack;

int createStack(OPRTstack*s)
{
    s->base=(char*)malloc(sizeof(char)*defaultsize);
    if(!s->base)return 0;
    s->top=s->base;
    s->stacksize=10;
    return 1;
}

int pop(OPRTstack *s,char *e)
{
    if(s->top==s->base)return 0;
    s->top--;
    *e=*(s->top);
    return 1;
}

int push(OPRTstack*s,char e)
{
    if(s->top-s->base>=s->stacksize)
    {
        s->base=(char*)realloc(s->base,sizeof(char)*(s->stacksize+increasesize));
        if(!s->base)return 0;
        s->top=s->base+s->stacksize;
        s->stacksize+=increasesize;

    }
    *(s->top)=e;
    s->top++;
}

int isEmpty(OPRTstack *s)
{
    if(s->top==s->base)return 1;
    else return 0;
}

char GetTop(OPRTstack *s)
{
    if(!isEmpty(s))
    {
        char*temp=s->top;
        temp--;
        return *(temp);
    }
    else return '!';//这样定义的话,栈里面不能存储!这个数据 
}

void showStack(OPRTstack*s)
{
    if(isEmpty(s))return ;
    for(int i=0;i<s->top-s->base;i++)
    {
        printf("%c ",s->base[i]);
    }
}

int createStack(NUMstack*s)
{
    s->base=(double*)malloc(sizeof(double)*defaultsize);
    if(!s->base)return 0;
    s->top=s->base;
    s->stacksize=10;
    return 1;
}

int pop(NUMstack *s,double *e)
{
    if(s->top==s->base)return 0;
    s->top--;
    *e=*(s->top);
    return 1;
}

int push(NUMstack*s,double e)
{
    if(s->top-s->base>=s->stacksize)
    {
        s->base=(double*)realloc(s->base,sizeof(double)*(s->stacksize+increasesize));
        if(!s->base)return 0;
        s->top=s->base+s->stacksize;
        s->stacksize+=increasesize;

    }
    *(s->top)=e;
    s->top++;
}

int isEmpty(NUMstack *s)
{
    if(s->top==s->base)return 1;
    else return 0;
}

double GetTop(NUMstack *s)
{
    if(!isEmpty(s))
    {
        double *temp=s->top;
        temp--;
        return *(temp);
    }
    else return -1;//这样定义的话,栈里面不能存储!这个数据 
}

void showStack(NUMstack*s)
{
    if(isEmpty(s))return ;
    for(int i=0;i<s->top-s->base;i++)
    {
        printf("%f ",s->base[i]);
    }
    printf("  ");
}

int isOPRT(char c)//判断c是不是运算符 
{
    if(c=='+'||c=='-'||c=='*'||c=='/'||c=='('||c==')'||c=='#')return 1;
    else return 0;
}

char compare(char a,char b)
{
    if(a=='+')
    {
        if(b=='*'||b=='/'||b=='(') return '<';
        else return '>';
    }
    else if(a=='-')
    {
        if(b=='*'||b=='/'||b=='(') return '<';
        else return '>';
    }
    else if(a=='*')
    {
        if(b=='(')return '<';
        else return '>';
    }
    else if(a=='/')
    {
        if(b=='(')return '<';
        else return '>';
    }
    else if(a=='(')
    {
        if(b==')')return '=';
        else if(b=='#') return '!';
        else return '<';
    }
    else if(a==')')
    {
        if(b=='(')return '!';
        else return '>';
        
    }
    else if(a=='#')
    {
        if(b==')')return '!';
        if(b=='#')return '=';
        else return '<';
    }
}

double calculate(double left,double right, char operators)
{
    switch(operators)
    {
        case '+':
            return left+right;
            
        case '-':
            return 1.0*left-right;
            
        case '*':
            return left*right;
            
        case '/':
            return 1.0*left/right;
    }
}

int main()
{
    OPRTstack oprt;//运算符栈 ***********
    NUMstack  num;//运算数字栈 *********
    NUMstack temp;//缓冲区,用于构建完整的运算数字 *********
    int build=0;//由若干数位构成的数字 
    double index;//某个数位上的数字 
    int complex=1;//10的幂次 ******
    char operators;//基本表达式中的四则运算符 
    double left,right;//基本表达式中左右运算数字 
    createStack(&num);
    createStack(&oprt);
    createStack(&temp);
    //printf("键入运算表达式,以#结束\n"); 
    push(&oprt,'#');
    char c=getchar();
    int error=0;//syntax error 标识符 
    while(c!='#'||GetTop(&oprt)!='#')
    {
        while(!isOPRT(c))//读入的是数字 
        {
            push(&temp,c-'0');
            c=getchar();
        }
        while(!isEmpty(&temp))//将读取到的数字字符存入缓冲区,构建完整的运算数字 
        {
            pop(&temp,&index);
            build+=(index*complex);
            complex*=10 ;
            
        }
        complex=1;
        if(build)push(&num,double(build));//将此运算数字压入栈num 
        build=0;
        
        if(isOPRT(c))//读入的是运算符 
        {
            switch(compare(GetTop(&oprt),c)){
                case '<':
                    push(&oprt,c);
                    c=getchar();
                    break;
                    
                case '=':
                    pop(&oprt,&operators);
                    c=getchar();
                    break;
                    
                case '>':
                    pop(&oprt,&operators);
                    pop(&num,&right);
                    pop(&num,&left);
                    push(&num,calculate(left,right,operators));//从num栈弹出两个运算数字,利用运算符栈顶元素进行计算 
                    break;
                    
                case '!':
                    printf("Syntax Error!");
                    error=1;
                    break;
            }
                
                    
            
        }
        if(error)break;
    }
    if(!error)printf("%d",int(GetTop(&num)));
    return 0;
}


迷宫求解

#include <stdio.h>
#include<stdlib.h>
int mg[11][10]= {{1,1,1,1,1,1,1,1,1,1},{1,0,0,1,0,0,0,1,0,1},{1,0,0,1,0,0,0,1,0,1},{1,0,0,0,0,1,1,0,1,1},{1,0,1,1,1,1,1,1,0,1},{1,0,0,0,1,0,0,0,0,1},{1,0,1,0,0,0,1,0,1,1},{1,1,1,1,1,0,0,0,1,1},{1,1,1,0,0,0,1,0,1,1},{1,1,0,0,0,0,0,0,0,1},{1,1,1,1,1,1,1,1,1,1}
};//地图
int M=9;//行数
int N=8;//列数
typedef struct
{
    int i;//当前方块行号
    int j;//当前方块列号
    int di;//下一个可走的相邻方块的方位号
} Box; //定义方块类型
typedef struct
{
    Box data[110];
    int top;//栈顶指针
} StType; //定义顺序栈类型
bool mgpath(int xi,int yi,int xe,int ye)//求解路径为:(xi,yi)->(xe,ye)
{
    int i,j,k,di,find;
    StType st;//定义栈st
    st.top=-1;//初始化栈顶指针
    st.top++;// 初始 方块 进栈
    st.data[st.top].i=xi;
    st.data[st.top].j=yi;
    st.data[st.top].di=-1;
    mg[xi][yi]=-1;
    while(st.top>-1)//栈不为空时循环
    {
        i=st.data[st.top].i;
        j=st.data[st.top].j;
        di=st.data[st.top].di;//取栈顶方块
        if(i==xe&&j==ye)//找到出口,输出路径
        {
            printf("有通路:");
            for(k=0;k<=st.top;k++)
            {
                printf("(%d,%d)",st.data[k].i,st.data[k].j);
                
            }
         
            return true;
        }
        find=0;
        while(di<5&&find==0)//站下一个可走方块
        {
            di++;
            switch(di)
            {
            case 0:
                i=st.data[st.top].i-1;
                j=st.data[st.top].j;
                break;
            case 1:
                i=st.data[st.top].i;
                j=st.data[st.top].j+1;
                break;
            case 2:
                i=st.data[st.top].i+1;
                j=st.data[st.top].j;
                break;
            case 3:
                i=st.data[st.top].i;
                j=st.data[st.top].j-1;
                break;
            }
            if(mg[i][j]==0)
                find=1;//找下一个可走相邻方块
        }
        if(find==1)//找到了下一个可走方块
        {
            st.data[st.top].di=di;//修改原栈顶元素的di值
            st.top++;//下一个可方块进栈
            st.data[st.top].i=i;
            st.data[st.top].j=j;
            st.data[st.top].di=-1;
            mg[i][j]=-1;//避免重复走到该方块
        }
        else//没有路径可走则退栈
        {
            mg[st.data[st.top].i][st.data[st.top].j]=0;
            st.top--;//将该方块退栈
        }
    }
    return false;
}
int main()
{
    if(!mgpath(1,1,M,N))
        printf("无解");
    return 0;
}

  • 5
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值