这是在传递 int num 时创建搜索函数的正确方法吗?使用链表库

Is this the proper way to create a search function while passing int num? Using a linked list libary

本文关键字:方法 链表 函数 int num 搜索 创建      更新时间:2023-10-16

头文件:

#ifndef LL_H
#define LL_H
// include this library to use NULL, otherwise use nullptr instead
#include <cstddef>
// include iostream so anything that includes this file can use cout
#include <iostream>
// Struct which will be the building block of our list
struct node
{
int val;
node* next;
};
// Contents of 11.h
// Linked list class definition
class LL
{
public:
LL();
bool removeFront();
bool removeBack();
node* search(int);
void print();
private:
node* head;
};
#endif

源文件:

#include "ll.h"
LL::LL()
{
head = NULL;
}
void LL::search (int num)//heading of the function
{
node* newNode = new node;
newNode->val = num;
newNode->next = NULL;
while (newNode == NULL)
{
if (newNode->val == num)
{
return newNode;
}
newNode = newNode->next; //point to the next node
}
return; //not sure if needed
}

该程序将在 名为"cmd.txt"的文本文件,它将指示要运行的操作。我们的程序应该实现一个C++类,该类将用于表示链表。

搜索应该看起来更像:

node* LL::Search(int num)
{
node* current = head;
while (current != null)
{
if (current->val == num)
{
return current;
}
current = current->next;
}
return null;
}

这是正确的格式

node* LL::search(int num)
{
node* newNode = new node;
newNode = head;
while (newNode->next != NULL)
{
if (newNode->val == num) 
{
return newNode;
}
newNode = newNode->next;
}
return NULL;
}