前言
欢迎大家积极在评论区留言发表自己的看法,知无不言,言无不尽,养成每天刷题的习惯,也可以自己发布优质的解题报告,供社区一同鉴赏,吸引一波自己的核心粉丝。
今天是七月集训第十二天:链表🔥🔥🔥
一、练习题目
二、算法思路
- 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、照着题解的思路去写的,我抽个时间画图加深下记忆。