【发布时间】:2016-02-06 22:08:50
【问题描述】:
我目前正在尝试编写一个函数,该函数将使用 stringstream 将链表中的数据转换为字符串。我不知道该怎么做,但已经以最少的功能启动了该功能。我怎样才能更好地编写我的函数来实现这一点?
SList.cpp:
/*
* SList.cpp
*
* written by Carlos D. Escobedo
* created on 26 Oct
*
* References: programmingforums.org (printing linked lists), stackoverflow
* (.h file linking issues)
*/
#include "SList.h"
SList::SList() {
head = NULL;
size = 0;
}
SList::~SList() {
SList::clear();
delete head;
}
void SList::insertHead(int value) {
if(head == NULL) {
head = new SLNode(value);
} else {
SLNode* temp = new SLNode(value);
temp->setNextNode(head);
head = temp;
}
size++;
}
void SList::removeHead() {
if (head != NULL) {
head = NULL;
size--;
}
}
void SList::clear() {
head = NULL;
}
unsigned int SList::getSize() const {
return size;
}
string SList::toString() const {
stringstream ss;
if (head != NULL) {
ss.str("");
} else {
int i = 1;
for (SLNode* n = head; n != NULL; n->getNextNode()) {
if (i < (size - 1))
ss << n->getContents() << ", ";
ss << n->getContents();
i++;
}
}
return ss.str();
}
【问题讨论】:
-
假设一切都正确实现,我的假设是正确的,并且
getNextNode()在for中返回指向下一个节点的指针(如果它是列表的末尾,则返回 NULL)您可以将n->getNextNode()更改为n = n->getNextNode()。 -
if (head != NULL) {不应该是if (head == NULL) {吗? (toString的第 2 行) -
你为什么不使用
std::list?迭代标准容器始终遵循相同的语法,无论是std::list、std::vector还是任何其他标准容器。 -
@Johny Mopp 是的!那应该是!很好,谢谢。
-
^ 因为这是家庭作业/作业。
标签: c++ linked-list iteration tostring