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

时间:2016-03-06 08:23:46

标签: c++ linked-list

这是一个简单的单链表程序,我试图在C ++中使用类。 以下是该计划:

#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;时会发生什么?是否会调用类的隐式构造函数?

2 个答案:

答案 0 :(得分:0)

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

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

此处head作为参考传递,因此会更新。

答案 1 :(得分:0)

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

这创建了一个Node实例。

Node * head;

从执行的角度来看,这条线路没有做任何事情。但是你有一个变量,将来可能会或可能不会指向Node。

head = NULL;

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

然后,在main范围内的变量head永远不会赋值。调用print ...

时仍为NULL