Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1327710
  • 博文数量: 115
  • 博客积分: 10011
  • 博客等级: 上将
  • 技术积分: 5785
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-28 09:13
文章分类
文章存档

2009年(23)

2008年(92)

我的朋友

分类: C/C++

2008-03-05 14:44:06

这是去年的一道题目,要求在一个小时之内完成,好长时间没写程序了,都不会了,其实本来也不会,嘿嘿!
下面是这个程序的代码,用的方法很笨,但是能完成,要是有时间限制的话,我也只能写到这个程度了。
方法很笨,将输入取到一个数组中然后将数组中的每一对括号的起始结束位置及其括号前的符号都取出来放在链表中,然后在处理这个链表,在数组中进行原地修改,就行了,具体代码如下:

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

#define N 20

typedef struct LNode{
  int start;
  int end;
  int distance;
  int pre;
  struct LNode *next;
}*List, LNode;


void input(int a[])
{
  printf("Please input :\n");
  int c, i;
  i = 0;
  while((c = getchar()) != '\n')
  {
    if(!isspace(c))
    {
      a[i++] = c;
    }
  }
  a[i] = '\0';
}

void output(int a[])
{
  int i = 0;
  while(a[i] != '\0')
  {
    if(a[i] == '#')
     i++;
    else
     printf("%c", a[i++]);
  }
}

void Link_insert(List list, List node)
{
  List p = list;
  if(p->next == NULL)
    p->next = node;
  else{
    while(p->next->distance < node->distance)
    {
      p = p->next;
    }
    node->next = p->next;
    p->next = node;
  }
  // printf("start %d end %d", node->start, node->end);

}
void getList(List list, int a[])
{
  List p = list;
  int i = 0;
  int count = 0;
  while(a[i] != '\0')
  {
    List node;
    if(a[i] == '(')
    {
      node = (List)malloc(sizeof(LNode));
      node->start = i;
      int j = i;
      while(a[j] != '\0')
      {
    if(a[j] == '(')
    {
     count++;
    }
    else if(a[j] == ')')
    {
     count--;
    }
    if(count == 0)
    {
     node->end = j;
     node->distance = j - i;
     node->next = NULL;
     node->pre = a[i - 1];
     Link_insert(list, node);
     break;
    }
    else
     j++;
      }
    }
    i++;
  }
}

void outList(List list)
{
  List p = list;
  while(p->next != NULL)
  {
    p = p->next;
    // printf("start %d end %d pre %c\n", p->start, p->end, p->pre);

  }
}

void change(List list, int a[])
{
  List p = list;
  List q = p->next;
  for(q; q != NULL; q = q->next)
  {
    if(q->pre == '-')
    {
     int i;
     for(i = q->start; i < q->end; i++)
     {
        if(a[i] == '+')
         a[i] = '-';
        else if(a[i] == '-')
         a[i] = '+';
     }
    }
    a[q->start] = '#';
    a[q->end] = '#';
    //    List_delete(q);


  }
}

int main()
{
  int a[N];
  List list = (List)malloc(sizeof(LNode));
  list->next = NULL;
  input(a);
  output(a);
  getList(list, a);
  outList(list);
  change(list, a);
  printf("\n");
  output(a);
  return 0;
}

阅读(1597) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:(修正)加减法去括号的程序

给主人留下些什么吧!~~