2017-04-05 107 views
0

我在大学的C++第一年,我的教授已经为我们在一个月内进行的最终测试分配了一些评论。据我所知,我已经做了所有其他的问题,但这两个问题有点奇怪。本质上,我的教授创建了一个名为ListA的类,该类使用动态分配的数组作为基础存储结构。考虑下面的代码,他要我们做两件事情:在类存储结构中使用动态分配的数组

  • 写出必要的私有变量
  • 写出类ListA

对于我写的构造函数的构造函数:

List::List(int size) 
    { 
     array = new ItemType[size]; 
     length = 0; 
     head = array[0]; 
    } 

对于必要的私有变量I wro te:

itemType* array; 
    int length; //to keep track how many elements are filled 
    itemType* head; //to create pointer for first element in array 
    itemType size; 

我只是不确定这些行是否正确。我觉得我很近,但我需要一些帮助。这里是.h文件:

typedef int itemType; 
class ListA 
{ 
public: 
List(int size); 
~List(); 
/* 
pre: an instance of lists exists 
post: true if list is empty, false otherwise 
*/ 
bool IsEmpty(); 
/* 
pre: an instance of list exists 
post: returns len 
gth of the list 
*/ 
int GetLength(); 
/* 
pre: an instance of list exists 
post: newItem is at the head of the list 
*/ 
void PutItemH(itemType newItem); 
/* 
pre: an instance of list exists and is not empty 
post: Returns the contents of the head of the list. 
*/ 
itemType GetItemH(); 
/* 
pre: an instance of list exists and is not empty 
post: head of the list is deleted 
*/ 
void DeleteItemH(); 
/* 
pre: an instance of list exists an 
d is not empty 
post: contents of list nodes are displayed on subsequent lines from head to tail 
*/ 
void Print(); 
/* 
Pre: an instance of list exists 
Post: returns true if the target is in the list, false otherwise 
/* 
bool Find(itemType 
target) 
/* 
Pre: an instance of list exists 
Post: if a node contains target, the node is deleted and true is returned, else false is returned. 
/*bool DeleteItem (itemType target) 
private: 
#notice that there are no member variables 
. See problem 14. 
}; 
+1

那么,你的问题到底是什么?什么不行?顺便说一句,你的'头'似乎是多余的,因为'数组'已经指向头部,除非你正在做类似圆形队列的事情。 –

+0

一般来说,调用某个列表并不会使它成为一个列表。数据类型通过它的行为,它的方法的语义有效地定义。只能在一个点上添加和删除元素的容器通常称为_stack_。在你的例子中,只有注释掉的DeleteItem方法不同于堆栈容器的方法。 – MSalters

回答

0

你不需要这么多的成员变量。

itemType* array; 
int length; //to keep track how many elements are filled 
itemType* head; //to create pointer for first element in array - Why ? 
itemType size; 

您可以修剪下来以下

itemType* array; 
int length; 
int size; 

构造函数应该是这样的:

List::List(int size):size(size), length(0) 
{ 
    array = new ItemType[size]; 
} 

这应该足以满足所有成员functions.Eg的需求:

bool ListA::IsEmpty() {return length == 0;} 
int ListA::GetLength() {return length;} 

length将在您将项目添加到您的基础阵列时递增。

+0

错误 - 如果列表方法允许更改头部,则需要头部。 (想到pust_front/pop_front方法)。事实上,由于列表节点是独立释放的,所以不清楚如何使用这些节点,您需要确切知道哪些节点是。 – MSalters