c++ - 链表C++,问题自学

标签 c++ linked-list self

        #include <iostream>
    using namespace std;



    struct Node
    {
        int item;   // storage for the node's item
        Node* next;   // pointer to the next node 
    };

  Node* addNode(Node*& head, int data , int& count) 
{
    Node * q;     // new node
    q = new Node;  // allocate memory for the new mode
    q->item = data;  // inserting data for the new node
    q->next = head;   // point to previous node ?? how would i do that? ( am i doing it correctly?)
    count++; // keep track of number of node
    head = q;
    return q;
}



    int main()
    {
        int a, count=0;
        int data;
        bool repeat;
        Node *head= NULL;   
        //^^ assuming thats creating the first node ^^
        do
        {
        cout << "please enter the data for the next node" <<endl;
        cin >> data;
        addNode(head, data, count);
        cout << "do you wish to enter another node? (enter true or false)" << endl;
        cin >>repeat;
        }
       while (repeat == true);


       // assuming this is the print function  
          while(head != NULL)
        {
            cout << "output" << temp->item << endl;
            cout << temp->next << endl;
        }

        system("pause");
        return 0; 
    }

好吧,我尝试在列表中添加一个新元素,我如何像 LIFO 内存(堆栈)一样移动头部,以便最后一个元素位于最顶部..

任何帮助将不胜感激!指针和节点最近在搅乱我的大脑....

最佳答案

temp 是一个未初始化的指针。所以——

temp-> item = a;  // temp is not initialized or pointing to a memory location
                  // that has Node object to use operator ->

首先,temp 需要使用new 分配内存位置。

temp = new Node;
temp -> item = a;

现在给它分配head。同样在 while 循环中也为子节点分配内存。并在程序终止前使用delete将所有从child获取的资源返回给head。

关于c++ - 链表C++,问题自学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5689432/

相关文章:

c++ - 为 arm : c++: error: unrecognized command line option ‘-mthumb’ ; did you mean ‘-mtbm’ ? 交叉编译 opencv

c++ - 将指针更改为指向指针的引用

algorithm - 为什么在给定要删除的节点时,单链表和双链表中的删除操作都不为 O(1)?

c++ - 类成员初始化的最佳实践

具有两个名称但不带 : 的 C++ 结构定义

java - 为什么要记录链表中移除的第一个元素?

c - 双向链表示例

ruby-on-rails - self 在 Rails 模型中的值(value)是什么?为什么没有明显的实例方法可用?

swift - self.property 或 Swift 中的属性

Python将其中一个参数代入self