【发布时间】:2015-12-26 08:38:13
【问题描述】:
所以我必须为班级创建一个链接列表,我被我的List::Current() 函数困住了。出于某种原因,我在尝试调用该函数时遇到了处理错误。
List.h
class List {
private:
struct Node {
int data;
Node* next;
Node() : next(NULL){} //define our own default constructor
Node(int data) : next(NULL), data(data){}
};
typedef struct Node* NodeRef;
NodeRef head;
NodeRef tail;
NodeRef iterator; //points to one node at a time
int size;
public:
int current();
List.cpp
// initialize the values when they are instantiated
List::List() : head(NULL), tail(NULL), iterator(NULL), size(0)
{}
int List::current() {
return iterator->data;
}
void List::push_front(int data) //Inserting a new node in the front of the list
{
if (size == 0) //If there is no nodes in the list, execute the if statement
{
head = new Node(data); //create a new node, and have head point to it
iterator = tail = head; //have tail point to the new node also.
}
else //If there are nodes in the list, execute the else statement
{
NodeRef newNode = new Node(data); //create a new node
newNode->next = head; //have the next pointer point to the head of the next node.
head = newNode; //have the head pointer point to the new node inserted at the beginning of the list
}
size++; //Increment the size counter
}
void List::push_back(int data) //Inserting a node at the end of a list
{
if (size == 0) //If there are no nodes in the list, execute the if statement
{
tail = new Node(data); //Create a new node and have the tail pointer point to it.
iterator = head = tail; //Have the head pointer point to the new node also.
}
else //If there is atleast 1 node in the list, execute the else statement
{
NodeRef newNode = new Node(data); //Create a new node
tail->next = newNode; //Have the tail
tail = newNode; //Have the tail pointer point to the new node.
newNode->next = NULL;
}
size++;
}
void List::begin() //Set the iterator to the head of the list
{
iterator = head;
}
void List::scroll() //Allows us to scroll through the list
{
if (iterator == NULL)
cout << "Iterator is pointing to null" << endl;
else
iterator = iterator->next;
}
LinkedList.cpp
#include "stdafx.h"
#include "List.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) {
List B; //Create a new list
B.push_front(5);
B.push_front(4);
B.push_front(3);
B.push_back(10);
cout << B.current() << endl;
system("PAUSE");
return 0;
}
我遗漏了一些代码,因为我不认为列出其他正常工作的函数对于理解这一点是必要的。如果您想要我可以发布的所有内容。
我认为这解决了我的问题。
【问题讨论】:
-
什么设置迭代器?如果没有设置,那么它要么是 0(在某些编译器的调试版本中)要么是随机的,其中任何一个都是未定义的行为,而不是你想要的。
-
你的课不完整,没有完整的例子,这个问题毫无意义。
-
好的,你已经添加了初始化,但是如果你没有在其他任何地方设置它,那么当你访问它时你仍然会得到未定义的行为。
-
@DominicMcdonnell,我认为这是我遇到的问题。现在我的问题是,我不太明白在哪里设置它。
-
@JonnyHenly,列表构造函数中的头部为 NULL
标签: c++ linked-list iterator