【发布时间】:2015-09-25 02:18:03
【问题描述】:
我在从头的末尾而不是开头读取链表时遇到了一点麻烦。我有一个插入函数,它读取输入的初始数字集,在列表中显示数字,然后将它们相加。它按照他们键入 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;
}
【问题讨论】:
-
双向链表可以简化事情,就像使用sentry node