What I have been asked to do: Q) A sentence consists of a list of characters terminated by a full stop. Write a function which returns a linked list of characters, where the characters are typed in by the user and added to the list. The returned list should include the full stop. It should be called as:
LinkedList<char> *sentence;
sentence = setUpSentence();
I have attempted to write pieces of this but I'm struggling as this is my first time working with linked lists & functions like this.
Main File
#include "LinkedList.h"
#include "ListNode.h"
#include "Node.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
LinkedList<char> *setUpSentence() {
//allocate the linked list objet
LinkedList<char> *sentence = new LinkedList<char>();
char ch;
do {
cout << "Enter characters to add, enter full stop to finish adding." << endl;
ch = cin.get();
sentence->addAtEnd(ch);
} while (ch != '.');
return sentence;
}
int main() {
//call the function, store the returned pointer in sentence variable
LinkedList<char> *sentence = setUpSentence();
//working with the linked list
sentence = setUpSentence();
cout << sentence->getAtFront() << endl;
//delete to avoid memory leak
delete sentence;
}
The error I am getting when attempting to run this attempt at beginning to write this function is :
after entering 1 character into the console and pressing enter, the loop continues and outputs "enter characters to add...." but this appears twice each time after entering a character?
Any ideas?
Code from functions from the LinkedList.h file that are used in my main:
template <typename T>
void LinkedList<T>::addAtEnd(T item)
{
if (size == 0)
addAtFront(item);
else
{
// ListNode<T>* temp = findAt(size - 1);
ListNode<T> *l = new ListNode<T>(item, last, nullptr);
last->next = l;
last = l;
size++;
}
}
template <typename T>
T LinkedList<T>::getAtFront()
{
if (size > 0)
{
current = first;
return first->item;
}
else return NULL;
}
edit: addAtFront Method from LinkedList.h file
template <typename T>
void LinkedList<T>::addAtFront(T item)
{
ListNode<T> *l = new ListNode<T>(item, NULL, first);
first = l;
if (last == NULL)
last = l;
size = 1;
}
addAtFrontis implemented correctly.sentencethen usecoutlater onsentence.setUpSentence()2 times. The first time will leak memory.