For example, my text file reads:
A 1
A 3
B
A 2
The goal is for the output to be 123
, but I have gotten everything but that.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Node
{
public:
char letter;
Node* next;
Node* prev;
Node(char cc)
{
letter = cc;
next = prev = nullptr;
}
};
string command;
char parameter;
Node* p = nullptr;
Node* rows[10];
int currentRow = 0;
void main()
{
for (int i = 0; i < 10; i++)
{
rows[i] = new Node('.');
rows[i]->next = nullptr;
rows[i]->prev = nullptr;
}
ifstream input("c:\\temp\\input.txt");
while (input.peek() != -1)
{
Node* c = rows[currentRow];
c = rows[currentRow];
while (c->next != nullptr)
c = c->next;
input >> command;
if (command == "B") { // Back Curser
//Moves curser back
}
else if (command == "F") { // Forward Curser
//Moves curser forward
}
else if (command == "A") // Add char Done
{
input >> parameter;
Node* newnode = new Node(parameter);
c->next = newnode;
newnode->prev = c;
}
}
input.close();
// display linked list
cout << endl;
for (int i = 0; i < 10; i++)
{
Node* t = rows[i]->next;
if (t != nullptr)
{
while (t != nullptr)
{
cout << t->letter;
t = t->next;
}
cout << endl;
}
}
}
At first I had tried c = c->prev
, but that did not work, as nothing was reorganized in my linked list.
I also attempted to create a brand new node that was hopefully then filled by the upcoming character, but my logic did not add up to that, and I ran into multiple issues.
For the lack of implementation details in 'B', I'll just help you fix 'A' instead.
You see, when moving the cursor back, you are now pointing to an element that already has a 'following node' (next
is no longer nullptr)
else if (command == "A") // Add char Done
{
input >> parameter;
Node* newnode = new Node(parameter);
newnode->next = c->next; //Link the new node to the previously following node (may be nullptr)
c->next = newnode;
newnode->prev = c;
}
Without the line I inserted, the previous next
of c
becomes inaccessible, leading to a memory leak.