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

来源:互联网 发布:windows系统资源监控 编辑:程序博客网 时间:2024/05/31 00:39

题目地址: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;}