最后一个位置的链表插入错误

问题描述

我用 C++ 编写了一个链表插入程序。当我添加一个函数在链表的最后一个位置插入一个节点时,我得到了一个奇怪的输出。似乎正在输出地址。这是我的代码。

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane fx:id="anchor" onKeyPressed="#keyPressed" prefHeight="650.0" prefWidth="750.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Sample2">
   <children>
      <ImageView fx:id="img3" fitHeight="50.0" fitWidth="50.0" layoutX="100.0" layoutY="100.0" onKeyPressed="#keyPressed" pickOnBounds="true" preserveRatio="true" style="-fx-view-order: 10;" translateZ="100.0">
         <image>
            <Image url="@../Şirine.png" />
         </image>
      </ImageView>
   </children>
</AnchorPane>

我得到的输出是:

#include <iostream>
using namespace std;

class Node
{
public:
   int data;
   Node *next;
   Node(int d)
   {
     data=d;
   }
};

class operations
{
public:
    Node *head;
    Node *ptr;

    void insertfirst(int d)
    {
        Node *newnode = new Node(d);
        newnode->next=NULL;
        if(head==NULL)
        {
            head=newnode;
        }
        else
        {
            newnode->next=head;
            head=newnode;
        }
    }

    void display()
    {
        Node *ptr;
        ptr=head;
        while(ptr!=NULL)
        {
            cout<<ptr->data<<" ";
            ptr=ptr->next;
        }
    }

    void insertafter(int key,int d)
    {
        Node *ptr;
        ptr=head;
        while(ptr->data!=key)
        {
            if(ptr->next==NULL)
            {
                cout<<"Key not found";
                return;
            }
            ptr=ptr->next;
        }
        Node *newnode=new Node(d);
        newnode->next=ptr->next;
        ptr->next=newnode;
    }

    void insertlast(int d)
    {
        Node *ptr;
        ptr=head;
        Node *newnode = new Node(d);
        newnode->next=NULL;
        while(ptr->next!=NULL)
        {
            ptr=ptr->next;
        }
        ptr->next=newnode;
    }
};

int main()
{
    operations o;
    o.insertfirst(4);
    o.insertfirst(3);
    o.insertafter(3,5);
    o.insertlast(1);
    o.display();
    return 0;
}

我的预期输出是:

3 5 4 1577825 1

我应该怎么做才能获得预期的输出?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)