c++ - 在链表前面添加新节点的问题

标签 c++ list reference new-operator singly-linked-list

<分区>

我正在尝试将一个新节点添加到链表的开头。所以新添加的节点成为链表的新头,链表的前一个头成为第二个节点。 这是我的代码:

    #include <iostream>
    #include <iomanip>

    class Node
    {
        public :
        int data ;
        Node * next ;
    } ;

    void printNodes(Node * node) ;
    void pushFront(Node * headReference, int newNode) ;

    int main()
    {
         Node * head = NULL,
         * second = NULL,
         * third = NULL ;

         head = new Node() ;
         second = new Node() ;
         third = new Node() ;

         head -> data = 1 ;
         head -> next = second ;

         second -> data = 2 ;
         second -> next = third ;

         third -> data = 3 ;
         third -> next = NULL ;

         pushFront(head, 4) ;
         printNodes(head) ;

         return 0 ;
   }

   //Printing the linked list nodes.
   void printNodes(Node * node)
   {
        int counter = 0 ;

        while(node != NULL)
        {
             ++ counter ;
             std::cout << "Node " << std::setfill('0')
                       << std::setw(2)
                       << counter
                       << " --> "
                       << node -> data
                       << std::endl ;

             node = node -> next ;
        }

        std::cout << "Linked List finished" << std::endl ;
   }

   //Inserting a new node on the front of the list.
   void pushFront(Node * headReference, int newData)
   {
        Node * newNode = new Node() ;

        newNode -> data  = newData ;

        newNode -> next = headReference ;

        headReference = newNode ;
   }

我期望的输出是:

节点 01 --> 4

节点 02 --> 1

节点 03 --> 2

节点 04 --> 3

链表完成

我得到的结果是:

节点 01 --> 1

节点 02 --> 2

节点 03 --> 3

链表完成

最佳答案

您必须通过引用传递头节点。例如

   void pushFront( Node * &headReference, int newData )
   {
        headReference = new Node { newData, headReference };
   }

否则函数处理头节点的拷贝。在函数内更改拷贝不会影响原始头节点的值。

另一种方法是 C 方法,当按引用传递时意味着通过指针传递对象。在这种情况下,函数看起来像

   void pushFront( Node * *headReference, int newData )
   {
        *headReference = new Node { newData, *headReference };
   }

可以称为

pushFront( &head, 4 );

关于c++ - 在链表前面添加新节点的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57803543/

相关文章:

c++ - 将 from_string 与提升日期一起使用

arrays - 分区求和算法

PHP 错误 : Unparenthesized `a ? b : c ? d : e` is deprecated. 使用 `(a ? b : c) ? d : e` 或 `a ? b : (c ? d : e)`

javascript - 在线 HTML/CSS/Javascript 学习引用替代 w3schools?

c# - 松散耦合、无引用的程序集——如何确保它在exe项目的\bin\Debug文件夹中进行调试?

c++ - 静态变量与成员

c++ - 两个项目之间的 MFC CString 链接器错误

php - 找出数据库中列出的 "not"目录中有哪些文件

c++ - 关于C++指针

c - 我们是否需要释放 GLIB 列表中的每个元素