2017-04-05 111 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