从链表的末尾开始读取值,而不是从开头

Reading values from a linked list starting from the end instead of the beginning c++

本文关键字:开头 读取 链表 开始      更新时间:2023-10-16

我从头部的末尾而不是开始阅读链表时遇到了一点麻烦。我有一个插入函数,它读入一组输入的数字,将这些数字显示在一个列表中,然后将它们相加。它按照他们输入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函数返回一些东西!