《七月集训》(第十三天)——双向链表

前言

        欢迎大家积极在评论区留言发表自己的看法,知无不言,言无不尽,养成每天刷题的习惯,也可以自己发布优质的解题报告,供社区一同鉴赏,吸引一波自己的核心粉丝。
        今天是七月集训第十二天:链表🔥🔥🔥
在这里插入图片描述

一、练习题目

        2296. 设计一个文本编辑器

二、算法思路

  • 1、2296. 设计一个文本编辑器:🔥🔥🔥🔥双向链表的应用。

三、源码剖析

// 2296. 设计一个文本编辑器
class TextEditor {
    struct BiNode
    {
        char c;
        BiNode *prev, *next;

        BiNode() {
            prev = next = nullptr;
        }

        BiNode(char _c) {
            c = _c;
            prev = next = nullptr;
        }
    };
    
    BiNode *dummyHead, *cursor;
public:
    TextEditor() {
        dummyHead = new BiNode();
        cursor = dummyHead;
    }
    
    void addText(string text) {
        BiNode *cursorNext = cursor->next;
        BiNode *now = cursor;
        for(int i = 0; i < text.length(); ++i) {
            now->next = new BiNode(text[i]);
            now->next->prev = now;
            now = now->next;
        }
        now->next = cursorNext;
        if(cursorNext) {
            cursorNext->prev = now;
        }

        cursor = now;
    }
    
    int deleteText(int k) {
        int cnt = 0;
        while(cursor != dummyHead && k--) {
            ++cnt;
            cursor->prev->next = cursor->next;
            if(cursor->next) {
                cursor->next->prev = cursor->prev;
            }
            cursor = cursor->prev;
        }
        return cnt;
    }

    string getCursorLeftString(int n) {
        string ret = "";
        BiNode *now = cursor;
        while (now != dummyHead && n--)
        {
            ret += now->c;
            now = now->prev;
        }
        reverse(ret.begin(), ret.end());
        return ret;
    }
    
    string cursorLeft(int k) {
        while (cursor != dummyHead && k--)
        {
            cursor = cursor->prev;
        }
        return getCursorLeftString(10);
    }
    
    string cursorRight(int k) {
        while (cursor->next != nullptr && k--)
        {
            cursor = cursor->next;
        }
        return getCursorLeftString(10);
    }
};
  • 1、照着题解的思路去写的,我抽个时间画图加深下记忆。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值