gpt4 book ai didi

c++ - 双向链表实现c++

转载 作者:行者123 更新时间:2023-11-27 23:06:03 27 4
gpt4 key购买 nike

我正在测试我的双向链表,但它没有显示任何内容。我正在插入学生数据然后尝试显示它。我只研究了推送功能并显示只是为了逐步进行。我是双向链表的新手。

#include <iostream>
#include <string>
#include "stdlib.h"
#include "time.h"
#include <ctime>
#include <cstdlib>
#include <time.h>
using namespace std;


class student
{
public:
int id; //student ID number
string name; //student’s name
string university; //student’ university
double GPA; //student’ GPA
};


//student list is a doubly linked list of students.
class studentList
{
private:
class node
{
public:
student data;
node * next;
node * prev;
};

node * head;

public:
studentList()
{

head = NULL;

}

//be sure to free all dynamically allocated memory!
~studentList()
{
delete head;
}

//return true if the list is empty, false if not
bool empty()
{
if ( head == NULL)
{
return true;
}
else
return false;

}

//insert student s into the front of the linked list
void push(student s)
{
node *tmp;
tmp = new node;

tmp->data = s;
tmp->next = head;
head = tmp;
}

//remove and return the student at the front of the list
student pop();

//locate and remove the student with given ID number
void removeStudent(int id);

//locate and return a copy of the student with given ID number
student getStudent(int id);

//locate the student with given ID number in list and set their GPA to gpa
void updateGPA(int id, double gpa);

//arrange students into increasing order based on either ID, name, or GPA. If
//variable 'field' has value "id", sort into increasing order by id.
//If 'field' has value "name", sort into alphabetical order by name.
//If 'field' has value "GPA", sort into order by GPA.
void sort(string field);

//a test function to simply display the list of students to the screen
//in the order they appear in the list.
void display()
{
node *current = head;

while (current!=NULL)
{
cout << &current->data << endl;
current = current->next;
}
}

};

int main()
{
studentList *my;
student *edwin;
edwin->name = "edwin";
edwin->university = "lsu";
edwin->GPA = 4.0;
edwin->id = 33;
my->push(*edwin);
my->display();









return 0;
}

最佳答案

你的问题就在这里,cout << &current->data << endl;

数据到底是什么?它是一些封装结构吗?我假设它是整个学生结构。如果是这种情况,那么您需要获取该结构,然后计算出它的各种成员。IE。cout << &current->data->name << endl;

也就是说,如果数据是 student* 类型,如果不是,那么您需要取消引用指向您的 student 结构的指针,然后计算它的成员。

此外,您在这里拥有的不是双向链表,实际上是单链表。双链表有一个 next 和 prev 指针指向列表中的下一个和上一个节点。

关于c++ - 双向链表实现c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23504801/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com