gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:14:29 25 4
gpt4 key购买 nike

<分区>

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

    #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

链表完成

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com