问题是,虽然在链表中添加数据没问题,但是当我们从列表中搜索内容时,它说列表是空的 但是如果我初始化这个
struct student * head = NULL;
struct student * curr = NULL;
在课外它工作正常是我的方法正确还是我们不能这样做?
#include <iostream>
using namespace std;
struct student{
int data = -100;
student * next;
};
class linkedlist{
struct student * head = NULL;
struct student * curr = NULL;
public:
void insertitem()
{
if(head == NULL){
struct student * temp = new student;
head = temp;
curr = temp;
temp->next = NULL;
cout << "Enter the data" << endl;
cin >> temp->data;
}
else if(head != NULL){
struct student * temp = new student;
curr->next = temp;
curr = temp;
temp->next = NULL;
cout << "Enter the data" << endl;
cin >> temp->data;
}
}
void searchitem(int x)
{
student * temp = new student;
temp = head;
if(temp != NULL)
{
while(temp->data != x)
{
temp = temp->next; //Traversal
if(temp == NULL){
break;
}
}
}
if(temp != NULL)
{
cout << "found" << endl;
cout << temp->data << endl;
}
else{
cout << "Not found" << endl;
}
}
};
int main()
{
int x = -100;
while(x != 0){
cout << "--------------------" << endl;
cout << "Enter 1 -- Insertion" << endl;
cout << "Enter 0--- Terminate" << endl;
cout << "--------------------" << endl;
cin >> x;
linkedlist l1;
switch(x)
{
case 1:
l1.insertitem();
break;
case 2:
l1.searchitem(6);
break;
}
}
return 0;
}
最佳答案
您在每次迭代时都创建了一个新的链表
。
将声明移出循环。
关于c++ - 使用类的 C++ 方法的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39727642/