为什么这个简单的链表程序无法正常运行
Why this simple linked list program does not function properly?
这是一个简单的单链表程序,我试图在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 作用域内的变量头永远不会被赋值。当您调用打印时,它仍然是空的...
相关文章:
- 在C应用程序中运行C++(带有STL)函数
- C++程序未运行
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 用时钟测量程序的运行时间
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- 多线程程序卡在优化模式下,但在 -O0 中正常运行
- 如何制作硬编码堆栈,而不是硬编码并保持程序正常运行
- 我的程序运行良好,可以复制对象,但是当我使用复制分配(=)时,它仍然可以正常运行.为什么不给错误
- 在 Ubuntu 16.04 的 usr/local/bin 中安装的 c++ 应用程序在从主目录执行时无法正常运行
- 如何调试正常运行但在 ide 中返回分段错误的程序?
- 当我尝试为我的程序提供 3 个输入时,它需要 4 个才能正常运行.为什么
- 程序无法在 dev C++ 上正常运行
- C++ 程序将无法正常运行
- 为什么这个程序在Clang或GCC下不能正常运行?
- For 循环结束自身并终止正在运行的程序,但在删除斜率计算语句时正常运行
- 读取元音并擦除元音的程序将无法正常运行
- 为什么这个简单的链表程序无法正常运行
- c ++程序无法在Mac上正常运行,但在Windows上可以
- c#包装到c++函数-运行一次,工作正常.运行两次,程序挂起
- C++程序无法正常运行