从链表的末尾开始读取值,而不是从开头
Reading values from a linked list starting from the end instead of the beginning c++
我从头部的末尾而不是开始阅读链表时遇到了一点麻烦。我有一个插入函数,它读入一组输入的数字,将这些数字显示在一个列表中,然后将它们相加。它按照他们输入IE 1 2 3的顺序,然后以降序方式显示它们,如下所示:123
例如,我想让程序从3开始,然后像这样计数:3.21程序编译和一切,但我不确定我在'insert_at_end'函数中出错的地方。任何建议都将非常感激。谢谢!
#ifndef LIST_H
#define LIST_H
#include <iostream>
using namespace std;
class List
{
public:
List();
~List();
int sum();
void insert(int value); // insert at beginning of list
void insert_at_end(int value);
void print();
private:
class Node
{
public:
Node(int value, Node *next)
{m_value = value; m_next = next;}
int m_value;
Node *m_next;
};
Node *m_head;
};
#endif
List::List()
{
m_head = NULL;
}
List::~List()
{
Node *ptr = m_head;
while (ptr != NULL)
{
Node *temp;
temp = ptr;
ptr = ptr->m_next;
delete temp;
}
}
void List::insert(int value)
{
m_head = new Node(value, m_head);
}
void List::print()
{
Node *ptr = m_head;
while (ptr != NULL)
{
cout << ptr->m_value << endl;
ptr = ptr->m_next;
}
}
int List::sum()
{
int total = 0;
Node *ptr = m_head;
while(ptr != NULL)
{
total = total + ptr->m_value;
ptr = ptr->m_next;
}
cout << "sum = " <<total<<endl;
}
void List::insert_at_end(int value)
{
m_head = new Node(value, m_head);
Node *ptr = m_head;
ptr->m_value = value;
ptr->m_next = NULL;
if(!value)
{
m_head = ptr;
return;
}
else
{
Node *last = m_head;
while(last->m_next)
{
last = last->m_next;
last->m_next = ptr;
}
}
}
#include <iostream>
using namespace std;
#include "list.h"
int main()
{
int number;
List list;
while(cin>>number)
{
list.insert_at_end(number);
//list.insert(number);
}
list.print();
list.sum();
return 0;
}
试试这个:
void List::insert_at_end(int value)
{
Node *ptr = new Node(value, NULL); // you mustn't break the m_head in this function
// you don't have to set the value to *ptr since it is already set above
if(!m_head) // value does no business here
{
m_head = ptr;
return;
}
else
{
Node *last = m_head;
while(last->m_next)
{
last = last->m_next;
}
last->m_next = ptr; // you mustn't break last->m_next here. get this line out of the loop
}
}
另外,不要忘记从sum
函数返回一些东西!
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- ifstream 读取以 开头的每个文件
- C++从文件中读取不同类型的数据,直到有一个以数字开头的字符串
- 从文件的开头读取,而不会浪费太多内存
- 是否可以在该用户注销后读取/打开用户密钥(HKEY_USERS中的密钥并以 s-1-5-21xxx 开头)
- 如何将ifstream返回到刚刚在C++中读取的行的开头
- 这是怎麽?在读取使用 Unicode 编码的文本文件后控制台输出的开头
- 在链表的开头插入时读取内存时出错
- C++fread读取文件开头的随机字符
- 从链表的末尾开始读取值,而不是从开头
- c++从文件开头读取到指定字节