POJ 2887 Big String

分析:给你一串字符,让你进行一系列插入和查询操作,查询时输出第p个字符,数组插入慢,链表查找快,于是我们用块状链表。

# include <stdio.h>
# include <malloc.h>
# include <string.h>
  typedef struct node
  {
      int len;
      char a[1005];
      struct node *next;
  }Node;
  int max;
  Node *Create()
  {
      int i,n,start=0;
      char s[1000005];
      Node *head=NULL,*p,*q;
      scanf("%s",s);
      n=strlen(s);
      max=n;
      while(start<n)
      {
          p=(Node *)malloc(sizeof(Node));
          if(n-start>1000)
            p->len=1000;
           else
            p->len=n-start;
            for(i=1;i<=p->len;i++)
                p->a[i]=s[start+i-1];
            p->next=NULL;
            if(head==NULL)
                head=p;
            else
                q->next=p;
            q=p;
            start+=p->len;
      }
      return head;
  }
  void Insert(Node *head)
  {
      int i,k;
      char c;
      Node *p;
      getchar();
      scanf("%c %d",&c,&k);
      if(k>max)
      {
          k=max+1;
          while(head->next)
          {
              k-=head->len;
              head=head->next;
          }
      }
      else
      {
          while(k>head->len)
          {
          k=k-head->len;
          head=head->next;
          }
          for(i=head->len;i>=k;i--)
          head->a[i+1]=head->a[i];
      }
      head->a[k]=c;
      (head->len)++;
      max++;
      if(head->len>1000)
      {
          p=(Node *)malloc(sizeof(Node));
          p->len=1;
          p->a[1]=head->a[head->len];
          (head->len)--;
          p->next=head->next;
          head->next=p;
      }
  }
  void query(Node *head)
  {
      int k;
      scanf("%d",&k);
      while(k>head->len)
      {
          k=k-head->len;
          head=head->next;
      }
      printf("%c\n",head->a[k]);
  }
  int main()
  {
      int t;
      char ch;
      Node *head=Create();
      scanf("%d",&t);
      while(t--)
      {
          getchar();
          scanf("%c",&ch);
          if(ch=='I')
            Insert(head);
          else
            query(head);
      }
      return 0;
  }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值