This is an interview question. What data structure would you use to store the text in a text editor?
On good old ZX-Spectrum one (or more, I do not know) text exditor used very simple structure.
There was one big buffer, which occupied all free RAM. Text was split in two parts at the cursor. Part before the cursor, was placed at the beginning of the buffer, and the rest at the end of the buffer. As text typed, data simply added to the end of first part, and when cursor is moved, text is copied forth and back.
Buffer layout:
Hello, World!
^------Cursor here
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|H|e|l|l|o|,| |W| <free> |o|r|l|d|!|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ^ ^ |
begin cur1 cur2 end
That's, how some edit operations was made:
Type a char: buffer[cur1++] = character
Backspace: cur1--
Cursor left: buffer[--cur2] = buffer[--cur1]
Cursor right: buffer[cur1++] = buffer[cur2++]
Buffer in action:
Hello, W..............orld!
Press right ^ ^
Hello, Wo..............rld!
Press backspace ^ ^
Hello, W...............rld!
Press 0 ^ ^
Hello, W0..............rld!
^ ^