這是一個簡單的單鏈表程序,我試圖在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;
會發生什麼?類的隱式構造函數被調用了嗎?
這不起作用。你可以在你的回答中加入更多的行 – Infinity
'head'的值是否改變。我認爲問題出在你的插入。但是,然後再次你的代碼不是OOD –