在C++中制作一个简单的链表
Making a simple linked list in C++
struct Node{
string val;
Node* next;
};
Node* makeList ()
{
string current;
Node* n;
Node* head= NULL;
Node* temp = n;
while(cin>>current && !cin.fail())
{
n = new Node;
n->val = current;
temp ->next = n;
temp = temp -> next;
}
n->next = NULL;
return n;
}
我正在尝试了解链表,这个函数 makeList() 应该使用字符串列表中的输入来创建并返回链表。老实说,我有点迷茫。任何帮助将不胜感激。
首先,你返回链表的最后一个节点。我认为您应该返回头部并将其分配给第一个节点。
其次,你对一个字符串使用 cin.fail() 我认为不应该这样做。 如果存在数据不匹配,cin.fail() 将起作用,对于字符串,我认为这种情况很少见。
该函数看起来有点像:
Node* makeList ()
{
string current;
Node* n;
Node* head= NULL;
Node* temp = n;
while(cin>>current && !cin.fail())
{
if(current == "0")
break;
n = new Node;
n->val = current;
temp ->next = n;
temp = temp -> next;
if(!head)
head = n;
}
n->next = NULL;
return head;
}
首先
,由于您的temp
代表了最后一个元素,因此我会在开头将其放入NULL(nullptr
更符合C++的精神,所以我将在下面的文本中使用它)。之后在while
循环中,当你添加一个新元素时,你应该写n->next=nullptr
,因为新元素的指针next
(如果你总是把它添加到列表的后面)将始终指向nullptr。在你的实现中,你的新元素n
总是指向自己。稍后在while循环中,您需要检查是否head==nullptr
,如果这是真的,则应将head
分配给head=n
的新元素。如果head
不等于nullptr
则需要将元素n
添加到后面的temp->next=n
。在循环的 and 中,您应该将 n
元素指定为 last- temp=n
(这必须在 else 块之外,因为它在上述两种情况下都是完成的)。
恐
怕答案首先有一些错误......
Node *make_link_list_from_input(){
string value;
Node *head = nullptr;
Node *current = nullptr;
Node *last = nullptr;
while (cin >> value){
current = new Node();
if(head== nullptr){
head = current;
}
if(last!= nullptr){
last->next=current;
}
last=current;
}
if(last != nullptr) {
last->next = nullptr;
}
return head;
}
相关文章:
- 在c++中用vector填充一个简单的动态数组
- 如何使用 samtools C API 构建一个简单的主.cpp文件
- 为什么一个简单的程序不能立即启动
- C++ - 在我尝试制作一个简单的计算器时有一个"uninitialized local variable y used"警告
- 为什么 MSVC C++编译器将一个简单的 Hello World 扩展为 4000 行汇编?
- 我写了一个简单的矢量程序,在其中我得到了以下输出。你能帮我理解它的输出吗?
- 如何使用 c++ 在命令行中创建一个简单的字符控制器?
- 对于 ~95% 写入/5% 读取线程安全的无序列图,有没有一个简单的解决方案?
- 在C++中创建一个简单的数据包路由器,如何跟踪"客户端"?
- 创建一个简单的前向迭代器,该迭代器在循环缓冲区的"end"处自动换行
- 我已经安装了用于c++编程的升华3,但在编写了一个简单的程序后,我遇到了以下错误
- 如何设置一个简单的CGAL+Qt程序
- 如何在一个简单的C++项目中使用Poco库
- 我创建了一个简单的程序,但有些地方不对劲
- Qt的新信号/时隙语法问题 - 连接到一个简单的函数
- 一个简单的 win32 多线程代码.这能行吗?
- 我正在尝试构建一个简单的程序来从 mysql 数据库中读取信息
- 创建一个简单的计算器,添加时遇到问题
- 我正在编写一个简单的客户端套接字应用程序,但在连接后服务器收到一个空缓冲区
- 为什么一个简单的"Hello World"风格的程序不能用Turbo C++编译?