c++ 访问单个链表中的特定值

c++ Accessing specific value in Single Linked List

本文关键字:访问 单个 链表 c++      更新时间:2023-10-16

我的列表包含一个名称和一个校园ID(CWID)。如何将列表中的 cwid 与我传入的整数进行比较?我在下面写了我正在尝试做的事情的比较的伪代码。

void check_cwid(studentList& list, int cwid) {
studentNode *p = list.head_;
while(p != nullptr){
 //Something like this 
   if *p.cwid() == cwid
  //do something
  p = p->next_;
}

我正在尝试完成上面代码中的内容。我只是不知道如何比较列表中的特定项目。以下是我的整个实践项目。

#include <iostream>
using namespace std;
class student {
public:
    student(const string& sname = "", int cwid = 0) : sname_(sname), cwid_(cwid) {}
    string sname() const {return sname_;}
    int cwid() const {return cwid_;}
    friend ostream& operator <<(ostream& os, student st){
        return os << endl << st.sname_ << endl << st.cwid_ << endl;
    }

private:
    string sname_;
    int cwid_;
};

struct studentNode {
    studentNode(const string& sname, int cwid, studentNode* next=nullptr) :st_(sname, cwid), next_(next) {}
    studentNode(student& st, studentNode* next=nullptr) : st_(st), next_(next) {}
    friend ostream& operator << (ostream& os, studentNode node) {
        return os << node.st_;
    }

    studentNode* next_;
    student st_;
};
struct studentList {
    studentList() : head_(nullptr), size_(0) {}
    studentNode* head_;
    size_t size_;
};

///******************** what im trying to do
void check_cwid(studentList& list, int cwid) {
    studentNode *p = list.head_;
    while(p != nullptr){


    }
}
int check_cwid(studentList& list, int cwid) {
studentNode *p = list.head_;
int list_size = list.size_;
while(list_size--){
 //Something like this 
   if (p -> st_.cwid() == cwid)
  //do something
   break;
   else
       p = p -> next_;
}