【问题标题】:Reading values from a linked list starting from the end instead of the beginning c++从链表中读取值,而不是从头开始 C++
【发布时间】: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

标签: c++ list class pointers


【解决方案1】:

试试这个:

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 函数返回一些东西!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多