首页 > 解决方案 > 只显示链表的最后一个元素

问题描述

我一直在尝试在 C++ 中创建一个链表。但只显示链表的最后一个元素。我已经搜索了错误,但我找不到它。我已经实现了从 c 语言中学到的逻辑。所有节点都正确连接。但我仍然找不到错误。此逻辑适用于 c 语言。请帮忙。

#include<iostream>

using namespace std;

class node{
public:
    int data;
    node *next;
}*head,*newnode,*temp;

node* getnode();
node* create(int);
void display(node*);

int main()
{
    int n;
    head=getnode();
    cout<<"Enter the no of nodes: ";
    cin>>n;
    head=create(n);
    display(head);
    return 0;
}

node *getnode()
{
    head=new node();
    head->next=nullptr;
    return(head);
}

node *create(int n)
{
    head=getnode();
    cout<<"Enter the value of node 1: ";
    cin>>head->data;
    temp=getnode();
    temp=head;
    for(int i=1;i<n;i++)
    {
        newnode=getnode();
        cout<<"Enter the value of node "<<i+1<<": ";
        cin>>newnode->data;
        newnode->next=nullptr;
        temp->next=newnode;
        temp=newnode;
    }
    return(head);
}

void display(node *head)
{
    while(head!=nullptr)
    {
        cout<<"->"<<head->data;
        head=head->next;
    }
}

标签: c++algorithmdata-structureslinked-listsingly-linked-list

解决方案


使用局部变量

*head,*newnode,*temp是全局变量。每次调用函数时,都会覆盖它们。使它们成为局部变量。

内存泄漏

您还使用以下方法在 main() 中泄漏内存:

head=getnode();

在 create() 中:

temp=getnode();

把它们放在一起

https://repl.it/repls/MedicalEquatorialFlashmemory#main.cpp


推荐阅读