为什么此代码用于单个链接列表不起作用

Why is this code for single linked list not working?

本文关键字:链接 列表 不起作用 单个 用于 代码 为什么      更新时间:2023-10-16

作为初学者,我尝试了这个单个链接列表程序以接受并首先显示到最后一个元素。在第一个元素中。我对语言并不熟悉,对指针概念是新手。这是一项作业。

#include <iostream>
using namespace std;
struct node
{
    int data;
    node* next;
};
class alpha
{
  public:
    node* head;
    node* last;
    node* n;
    node* p;
    int x;
    char ch;
    void input()
    {
        cout << "Enter the element..";
        cin >> x;
        insert(x);
        cout << "Do you want to add more?";
        cin >> ch;
        if (ch == 'y')
        {
            input();
        }
        else
        {
            display();
        }
    }
    void insert(int x1)
    {
        n = new node;
        n->data = x1;
        if (head == NULL)
        {
            head = n;
            last = n;
        }
        else
        {
            n->next = NULL;
            last->next = n;
            last = n;
        }
    }
    void display()
    {
        p = head;
        while (p != NULL)
        {
            cout << p->data;
            p = p->next;
        }
    }
};
int main()
{
    alpha o;
    o.input();
    return 0;
}

已经指出的大错误是构造函数没有初始化。我也建议将一些数据成员移至私有,并将其中一些数据成员置于本地。

#include <iostream>
using namespace std;
struct node
{
    int data;
    node* next;
};
class alpha
{
private:
    node* head;
    node* last;
public:
    alpha() {
        head = NULL;
        last = NULL;
    }
    void input()
    {
        int x;
        char ch;
        cout << "Enter the element..";
        cin >> x;
        insert(x);
        cout << "Do you want to add more?";
        cin >> ch;
        if (ch == 'y')
        {
            input();
        }
        else
        {
            display();
        }
    }
    void insert(int x1)
    {
        node* n = new node;
        n->data = x1;
        if (head == NULL)
        {
            head = n;
            last = n;
        }
        else
        {
            n->next = NULL;
            last->next = n;
            last = n;
        }
    }
    void display()
    {
        node* p = head;
        while (p != NULL)
        {
            cout << p->data;
            p = p->next;
        }
    }
};
int main()
{
    alpha o;
    o.input();
    return 0;
}

正如某人建议的那样,请实现destructor〜alpha((,以避免泄漏节点实例。