⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stack.c

📁 数据结构实验
💻 C
字号:
/* 标准文档模板 */

#include <stdio.h>
#include <conio.h>

#define TRUE 1
#define FALSE 0
#define MAX 20

struct stack      /*定义栈s*/
{
    char date[MAX];
    int top;
}s;

int push(char ch)  /*压栈*/
{
  if(s.top==MAX)  return FALSE;     /*判满*/
  else
  {
   s.date[s.top]=ch;
   s.top++;
   return TRUE;
   }
}

char gettop()
{
    int ch2;
    s.top--;
    if(s.top==-1)/*判空*/
   {
    s.top++;
    return FALSE;
    }
    ch2=s.date[s.top];
    s.top++;
    return ch2;
}

char pop()          /*出栈*/
{
   char ch1;
   s.top--;
   if(s.top==-1)/*判空*/
   {
    s.top++;
    return FALSE;
    }
   else
   {
    ch1=s.date[s.top];
    return ch1;
   }
}

int main(void)                     /*主函数*/
{
 /* 读入文件 */
  FILE *fp;
  char ch0,ch,filename[20];
  s.top=0;
  printf("please input the pass of your text document:\n");
  scanf("%s",filename);
  if((fp=fopen(filename,"r"))==NULL) /*打开文件*/
    {
        printf("Can not open file!\n");
        exit(0);
    }
  /*ch=getchar();/*接收scanf语句最后输入的回车符*/  */
  ch=fgetc(fp);/*接收输入的第一个字符*/

  while(ch!=EOF)
  {
    /*putchar(ch);*/
    /*读入一个符号,进行匹配*/

    ch0=gettop(s);
    if(ch0==FALSE)   /*如果操作未完成时,栈空*/
    {
        push(ch);
        ch=fgetc(fp);
        /*continue;*/
    }
    else if(ch0=='('&&ch==')') /*是否匹配比对*/
      {
       pop();
       printf("matched:%c,%c\n ",ch0,ch);
       }
       else if(ch0=='['&&ch==']')
       {
        pop();
        printf("matched:%c,%c\n ",ch0,ch);
       }
       else if(ch0=='{'&&ch=='}')
       {
        pop();
        printf("matched:%c,%c\n ",ch0,ch);
       }
    else               /*该字符未匹配,压栈*/
    push(ch);
    ch=fgetc(fp);
  }
  ch=gettop();
  if(ch==FALSE) printf("all successfully matched yet!\n");
  else
  {
  printf("Not matched, those charactor left in stack:\n");
  ch0=pop();
  while(ch0!=FALSE)
  {
    putchar(ch0);
    ch0=pop();
  }
  }
  getch();
  return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -