链表类List
这个类是为了给GeneralTree提供Queue队列操作才创建的。
因为GeneralTree使用层次遍历的时候,必须要使用这样一个队列。当然如果你没有这样一个队列,但是你在每个节点那里设置了计数器,那么你还是可以完成一个层
次遍历操作。
这里为了保持GeneralTreeNode的最简单性,所以没有添加计数器属性。
下面是List类的具体代码:
/* * create by chico chen * date: 2009/02/02 / #ifndef LIST_H #define
LIST_H template
ListNode() { next = NULL; } ListNode(T & data) { this->data = data; next =
NULL; } ListNode(T & data, ListNode
= next; } ~ListNode() { next = NULL; } }; template
private: int length; ListNode
0; } List(ListNode
ListNode
delete head; head = tempHead; } length = 0; } bool IsEmpty() { return 0 ==
length; } // the coral function to insert the node // pre : none // post: no
matter what kind of situation, the function can work. void Insert(ListNode
node, int index) { if(0 == index) { // insert in the front if(NULL == head) {
head = node; } else { node->next = head; head = node; } } else { if(NULL ==
head) { head = node; } else { if(index >= length || index < 0) { index =
length; } ListNode
temp = temp->next; } temp->next = node; } } length ++; } ListNode
GetHead() { return this->head; } // pre: list is not empty // post: return the
last element. ListNode
ListNode
tempHead->next; } return tempHead; } // pre: node is not NULL // post: return
the node’s next node ListNode
node) { return node->next; } } // pre: begin at zero, and the index is less
than the length of the list // post: if index is -1, then return the last //
post: if index is not -1 and less than zer, or bigger than the length, throw
exception. ListNode
index) { // get the last temp = GetTail(); } else if(0 <= index && index <
length) { ListNode
= tempHead->next; } temp = tempHead; } else { throw “out of list”; } return
temp; } void DeleteHead() { ListNode
delete tempHead; this->length–; } // pre: head is not NULL // post: delete
the last one and length subtract 1 void DeleteTail() { if(NULL == head)
return; ListNode
= tempTail->next; } delete tempTail; length–; } // pre: head may be not NULL
// post: if index is equal to -1, then delete tail element // post: if index
is equal to 0, then delete the head // post: if it is bigger than the length,
or less than 0, throw exception // post: delete one node at index and length
subtract 1 void DeleteAt(int index) { if(-1 == index) { DeleteTail(); } else
if(0 == index) { DeleteHead(); } else if(0 < index && index < length) {
ListNode
temp->next = dNode->next; delete dNode; length --; } else { throw “out of
List”; } } }; #endif