我正在测试我的双向链表,它没有显示任何内容。我正在插入一个学生数据,然后尝试显示它。我只是在推送功能和显示上做了一些工作,只是为了逐步了解它。我不熟悉双向链表。
#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 << ¤t->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;
}发布于 2014-05-07 05:29:59
您的问题存在于此,请参阅<<?t->data << endl;
数据到底是什么?它是某种封装的结构吗?我假设它是整个学生结构。如果是这种情况,那么您需要获取该结构,然后查看它的各个成员。即cout << t->data->name << endl;
也就是说,如果数据是学生类型*,如果不是,那么你需要取消对学生结构的引用,然后清除它的成员。
这里你得到的也不是一个双向链表,而是一个单链表。双向链表具有指向列表中的下一个和前一个节点的next和prev指针。
发布于 2014-05-07 05:34:20
您未正确初始化edwin。这条线
student *edwin;只是声明了一个指向student结构的指针。它不会为它分配内存。在此之后立即使用edwin->name是不正确的。
只需使用结构而不是指向它的指针student edwin; edwin.name="...";。无论如何,您的push会复制该结构。
正如在40two中注意到的,您也没有初始化my。我建议你自己试着找到正确的初始化方法。
另一个可能是错误的地方:
cout << ¤t->data << endl;你能解释一下这条线吗?你为什么不做cout << current->data.name
还要注意,您从未在node中设置过prev指针(尽管您有此字段)。所以它不是一个正确的双向链表(本质上,它是一个单链接表)。
https://stackoverflow.com/questions/23504801
复制相似问题