WHU1478----2014年武大邀请赛H题----双向链表

题目地址:http://acm.whu.edu.cn/land/problem/detail?problem_id=1478

这个题目的意思很简单,提供几种操作

光标左移,右移

插入一个字母

删除一个字母

这个完全可以利用双向链表来模拟,左移就将指针左移,右移同理

建立一个空头的双向链表,每当要插入的时候在当前光标的后面插入

如果需要删除的话,就将当前光标的内容删除,并将pos往前移,即指向前一个。

另外,如果光标在头,那就不动了,我一开始将删除理解层了del,但应该是backspace,所以,到头了就无法backspace了

并且因为你每次都要申请空间,那么每一组数据后,显示之后要记得清空空间,不然要MLE的。

下面上我的代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const int maxn = 1000000+10;

char a[maxn];
int t;

struct node
{
    char data;
    node * pre;
    node * next;
};

void out(node *h)
{
    while(h->next != NULL)
    {
        node *p=h;
        h=h->next;
        printf("%c",h->data);
        delete p;
    }
}

int main()
{
    scanf("%d",&t);
    for(int ca=1;ca<=t;ca++)
    {
        scanf("%s",a);
        int len = strlen(a);

        node *head = new node;
        head->data = NULL;
        head->pre = NULL;
        head->next = NULL;
        node *pos = head;
        for(int i=0;i<len;i++)
        {
            //cout<<"i "<<a[i]<<endl;
            if(a[i] == '<')
            {
                if(pos->pre != NULL)
                {
                    pos = pos->pre;
                }
            }
            else if(a[i] == '>')
            {
                if(pos->next != NULL)
                    pos = pos->next;
            }
            else if(a[i] == '-')
            {
                if(pos->data !=NULL)
                {
                    if(pos->next == NULL)
                    {
                        node *f=pos->pre;
                        f->next = NULL;
                        node *tmp = pos;
                        pos = f;
                        delete tmp;
                    }
                    else
                    {
                        node *f=pos->pre;
                        node *n=pos->next;
                        node *t=pos;
                        f->next = n;
                        n->pre = f;
                        pos = f;
                        delete t;
                    }
                }
            }
            else
            {
                node *in = new node;
                in->data = a[i];
                node *n = pos->next;
                in->next = n;
                if(n!=NULL)n->pre = in;
                pos->next = in;
                in->pre = pos;
                pos=in;
            }
        }
        printf("Case %d: ",ca);
        out(head);
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值