gpt4 book ai didi

c++ - 在 C++ 中打印链表

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

我的以下代码只打印第一个元素。在 print_list() 函数中,它在打印第一个元素后停止。它表示在第一个元素之后,head->next0。不应该指向第二个元素吗?

我只想打印整个列表。

#include<iostream>
#include<cstdlib>
using namespace std;
struct node {
int x;
node *next;
};
node* add_element(node*);
bool is_empty(node*);
void print_list(node*);
node* search(node*);

int main()
{
node *head;
head=NULL;
node* current=head;
for(int i=0;i<5;i=i+1)
{
if (current==NULL)
{
current=add_element(current);
head=current;
}
else{
current=add_element(current);
}
}
cout<<head->next<<endl;

// DOUBT: head->next gives NULL value. It should give me pointer to 2nd node
print_list(head);
}
node* add_element(node* current)
{
node* temp;
temp=new node;
temp->next=NULL;
cout<<"enter element"<<endl;
cin>>temp->x;
current=temp;
return current;
}
bool is_empty(node* temp)
{
return temp==NULL;
}
void print_list(node* temp)
{
if (is_empty(temp)==false)
{
cout<<"here temp(head)"<<temp->next<<endl;
while(temp!=NULL)
{
cout<<temp->x<<endl;
temp = temp->next;
}
}
}

最佳答案

打印函数打印第一个元素,因为链表中只有一个节点!实际上错误出现在 add_element(node*) 函数中,你用新节点覆盖了 head 节点的地址(因此有内存泄漏),如下所示:

  node* add_element(node* current)
{
node* temp;
temp = new node; <---" You allocated memory"
temp->next = NULL; <---" Set next NULL"
cout<< "enter element" << endl;
cin>> temp->x; <---" Assign a value in new node"

// Replace below two line with suggested
current = temp; <---"MISTAKE: Overwrite first node"
"temp next is NULL so losing address of other nodes"

return current; <--- "return first node"
}

新节点(即第一个节点)的下一个为 NULL,因此打印函数仅打印第一个节点的值。

建议:

您应该更正如下以将新节点添加为链表中的第一个节点:

temp -> next = current;  // new nodes next if present first node
return temp; // new code becomes first node

注意 current 最初应该是 NULL。

根据我在 add_element() 函数中的建议,也将 main() 中的 for 循环代码更改为如下:

for(int i=0; i < 5; i = i + 1){
current = add_element(current);
}
head = current;

并检查 Codepade 处的工作代码(我使用 y = 100 变量添加值,而不是用户输入)。

编辑 添加新节点:

您需要检查新节点是否是第一个节点(阅读评论)。

  // returns first node address in linked list = head 
node* add_element(node* head){
node *temp, *new_nd;

// Create new node
new_nd = new node;
new_nd->next = NULL;
cout<<"enter element"<<endl;
cin>>new_nd->x;

// Is new node is the first node?
if(!head)
return new_nd;

// move to last
temp = head;
while(temp->next) temp = temp->next;

// add new node at last
temp->next = new_nd;

// return old head
return head;
}

同样简单的 main() 如下:

int main(){
node *head = NULL;
for(int i = 0; i < 5; i = i + 1){
head = add_element(head);
}
print_list(head);
}

检查这个working code .

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

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