为什么这个简单的链表程序无法正常运行

Why this simple linked list program does not function properly?

本文关键字:程序 正常运行 链表 简单 为什么      更新时间:2023-10-16

这是一个简单的单链表程序,我试图在C++中使用class制作。以下是程序:

#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
class Node
{
  int data;
  Node *next;// to store the address of next node
  public:
    void Insert(Node*, int);
    void Print(Node*);
    bool isPalindrome(Node*);
};
void Node:: Insert(Node *head, int info)
{
  Node *temp;
  temp = new Node;
  temp->data = info;
  temp->next = NULL;
  // check if the head node is empty
  // if yes then copy address of new node(temp) into head;
  if(head == NULL)
  {
    head = temp;
  }
  Node *temp2;// for traversing upto the last node
  temp2 = head;
  while(temp2->next != NULL)
    temp2 = temp2->next;
  temp2->next = temp;// assigned the address of new node at the end of the list
}
void Node:: Print(Node *head)
{
  if(head == NULL)
  {
    std::cout<<"n The Linked list is empty "<<std::endl;
    return ;
  }
  else
  {
    while(head != NULL)
    {
      std::cout<<" "<<head->data;
      head = head->next;
    }
  }
}
int main()
{
  Node obj;
  Node * head;
  head = NULL;
  int choice, info;
  while(1)
  {
    std::cout<<"n Enter your choice : n";
    std::cout<<"n 1. Insert Element n 2. Print Element n 3. EXIT n: ";
    std::cin>>choice;
    switch(choice)
    {
      case 1:
        std::cout<<"n Enter a element  : ";
        std::cin>>info;
        obj.Insert(head, info);
        break;
      case 2:
        obj.Print(head);
        break;
      case 3:
        exit(0);
    }
  }
  return 0;
}

此程序的问题:

输出实例:

 Enter your choice : 
 1. Insert Element 
 2. Print Element 
 3. EXIT 
: 1
 Enter a element  : 1
 Enter your choice : 
 1. Insert Element 
 2. Print Element 
 3. EXIT 
: 1
 Enter a element  : 2
 Enter your choice : 
 1. Insert Element 
 2. Print Element 
 3. EXIT 
: 2
 The Linked list is empty 
 Enter your choice : 
 1. Insert Element 
 2. Print Element 
 3. EXIT 
打印链表

时,它显示:链表为空。为什么?

在main():

Node obj;// this I have create to call member functions of the class.
  Node * head;
  head = NULL; 

执行Node *head;时会发生什么? 是否调用类的隐式构造函数?

main中,您没有更新 head 的值 - 您将其作为值传递给 Insert 。将Insert更改为:

void Node::Insert(Node *&head, int info)

在这里,head作为引用传入,因此将被更新。

Node obj;// this I have create to call member functions of the class.

这将创建一个节点实例。

Node * head;

从执行的角度来看,这条线有点不做任何事情。但是您有一个变量,将来可能会也可能不会指向节点。

head = NULL;

您现在已将该变量设置为 NULL,这是标准的说法,它不指向任何内容。

然后,在 main 作用域内的变量头永远不会被赋值。当您调用打印时,它仍然是空的...