gpt4 book ai didi

C++ 函数返回链表

转载 作者:行者123 更新时间:2023-11-30 03:34:39 24 4
gpt4 key购买 nike

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

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

我曾尝试编写其中的一些内容,但我正在努力,因为这是我第一次使用这样的链表和函数。

主文件

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

我在开始编写此函数时尝试运行此尝试时遇到的错误是:

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?

有什么想法吗?

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

最佳答案

我不知道你为什么要在返回语句中递归调用 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!
}

关于C++ 函数返回链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41893824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com