我在从头尾而不是开头读取链表时遇到了一些麻烦。我有一个插入函数,它读取输入数字的开始集合,将数字显示在列表中,然后将它们相加。它按照他们键入 IE 1 2 3 的顺序排列,然后以降序方式显示它们,如下所示: 1个 2个 3
例如,我想让程序从 3 开始,然后这样计数: 3个 2个 1
程序可以编译,但我不确定“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
函数返回一些东西!
关于c++ - 从链表的末尾而不是从头开始读取值 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32773757/