【问题标题】:Three elements in one node of a linked list链表的一个节点中的三个元素
【发布时间】:2015-09-25 18:20:19
【问题描述】:

我正在尝试理解链表,但遇到了困难。我想将三个元素放在一个节点中,然后打印出多个节点。但是,我只能打印节点的第一个元素。 例如: 输入:1、2、3 输出:1 NULL

struct node
{
    int Intx, Inty, Intz;
    struct node *p;
}

class linked
{
public:
    node* create_node(int first, int second, int third);
    int Intx, Inty, Intz;
    void insert();
    void display();
}

main()
{
    linked sl;
    sl.insert();
    sl.display();
}

node *linked::create_node(int first, int second, int third)
{
    Intx = first;
    Inty = second;
    Intz = third;
    struct node *temp, *p;
    temp = new (struct node);
    if (temp == NULL)
    {
        cout << "Not able to complete";
    }
    else
    {
        temp->Intx = first, Inty = second, Intz = third;
        temp->next = NULL;
        return temp;
    }
}

void linked::insert()
{
    int Intx, Inty, Intz;
    cout << "Enter First Element for node: ";
    cin >> Intx;
    cout << "Enter Second Element for node: ";
    cin >> Inty;
    cout << "Enter Third Element for node: ";
    cin >> Intz;
    struct node *temp, *s;
    temp = create_node(Intx, Inty, Intz);
    if (start == NULL)
    {
        start = temp;
        start->next = NULL;
    }
    else
    {
        s = start;
        start = temp;
        start->next = s;
    }
    cout << "Element Inserted." << endl;
}

void linked::display()
{
    struct node *temp;
    cout << "Elements of list are: " << endl;
    while (temp != NULL)
    {
        cout << temp->Intx, Inty, Intz;
        temp = temp->next;
    }
    cout << "NULL" << endl;
}

【问题讨论】:

  • 需要分号';'在结构和类定义之后。 main 必须返回 int。具有非 void 返回类型的函数(例如 create_node)必须为函数中的所有路径返回一个值。逗号运算符滥用已包含在答案中。 Injblue,您需要深入研究教科书并进行一些基本的程序构建,然后才能得到有效的帮助。当心你可以简单地剪切和粘贴答案,因为这会导致你学习成为Cargo Cult Programmer

标签: c++ linked-list nodes element


【解决方案1】:
temp-> Intx = first, Inty = second, Intz = third;

用逗号分隔事物并不像您认为的那样。您应该使用三个语句,并且必须在每个语句中包含 temp-&gt;

temp->Intx = first;
temp->Inty = second;
temp->Intz = third;

如果你真的想使用逗号运算符,你可以,但你仍然需要temp-&gt; 来处理所有三个分配。

同样,您在display 中使用的逗号也不是您想要的

cout<< temp->Intx, Inty, Intz;

应该是

cout<< temp->Intx << "," << temp->Inty << "," << temp->Intz;

或者类似的东西,取决于你想要的格式

【讨论】:

    【解决方案2】:

    而不是讨论代码中的问题。我宁愿建议您了解链表算法背后的逻辑。这将帮助您成长。

    链接Link1: Youtube tutLink 2 将为您提供链接列表算法工作原理的基本知识。

    1. 由于程序是使用 C++ 编写的。 Link 1 是一个 youtube 教程,提供了在 Visual Studio 中使用 C++ 编程的每个链表操作的逐步说明。这可能有助于您了解-&gt; 运算符的正确用法。此外,它还可以帮助您了解对象与其成员之间的关系。

    2. 虽然链接 2 仅在理论上有助于链接列表作为数据结构如何增长以及如何维护它。

    【讨论】:

    • 虽然我同意评估和意图,但您应该总结链接以使其成为真正的答案。目前这是评论,不是答案
    • @user4581301 很抱歉,我会将其作为评论提供,但没有足够的声誉来发表评论。我试图修复我的答案。但如果你建议我很乐意标记我的答案以保持堆栈清洁。
    猜你喜欢
    • 2016-07-01
    • 2020-02-16
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多