C ++函数返回链表

时间:2017-01-27 12:16:36

标签: c++ templates input linked-list

我被要求做的事情: Q)句子由一个句号终止的字符列表组成。编写一个返回字符链表的函数,用户输入字符并添加到列表中。返回的列表应包括句号。 它应该被称为:

LinkedList<char> *sentence;
sentence = setUpSentence();

我曾尝试写过这些内容,但我正在努力,因为这是我第一次使用链接列表&amp;像这样的功能。

主文件

#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;
    }

尝试运行此尝试以开始编写此函数时出现的错误是:

  

将1个字符输入控制台并按回车键后,循环继续并输出&#34;输入字符以添加....&#34;但是在输入角色后每次出现两次?

有什么想法吗?

我在main中使用的LinkedList.h文件中的函数代码:

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;
}

编辑: LinkedList.h文件中的addAtFront方法

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;
}

1 个答案:

答案 0 :(得分:2)

我不知道你为什么要在return语句中对setUpSentence()进行递归调用,这没有意义。我认为它应该是这样的:

LinkedList<char> * setUpSentence() {
    // make sure to allocate the linked list object
    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() {
    // calling the function, store the returned pointer in sentence variable
    LinkedList *sentence = setUpSentence();

    // ... working with the linked list ...

    delete sentence;  // don't forget to delete it to avoid memory leak!
}