字符串链表存储的删除和插入

/*
题目描述:
对于长度为n的字符串有k个操作:
1 pos c 代表在pos这个位置之后插入字符c
2 pos 代表删除pos这个位置的字符
结束操作后输出改变后的字符串和字符串长度

input:
8 3
dhsuxjdh
1 3 d
1 9 a
2 5

output:
dhsdxjdha 9
*/
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define dep(i,a,b) for(int i=(a);i>=(b);--i)
#define pb push_back
const int maxn=(int)2e3+100;
typedef struct node{
    char data;
    struct node *next;
}LNode;
LNode *First,*P,*tmp;
void Insert(int pos,char c){
    P=First;
    rep(i,2,pos) P=P->next;
    LNode *new_node;
    new_node=new LNode;
    new_node->data=c;
    new_node->next=P->next;
    P->next=new_node;
}
void Delete(int pos){
    P=First;
    if(pos==1) First=First->next;
    else{
        rep(i,3,pos) P=P->next;
        P->next=P->next->next;
    }
}
void print(){
    int cnt=0;
    P=First;
    while(1){
        if(P->next==NULL) break;
        printf("%c",P->data);
        P=P->next;
        cnt++;
    }
    printf(" %d\n",cnt);
    return;
}
int main(){
    First=new LNode; P=First;
    int n,k;char str[maxn];scanf("%d%d%s",&n,&k,str+1);
    P->data=str[1];str[n+1]='\0';
    rep(i,2,n+1){
        tmp=new LNode;
        tmp->data=str[i];
        P->next=tmp;
        P=tmp;
    }
    P->next=NULL;
    while(k--){
        int op;scanf("%d",&op);
        if(op==1){
            int pos;char c;scanf("%d %c",&pos,&c);
            Insert(pos,c);
        }else{
            int pos;scanf("%d",&pos);
            Delete(pos);
        }
    }
    print();
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值