1 回答

TA貢獻1880條經驗 獲得超4個贊
ifndef __LINKEDLIST_HPP__
#define __LINKEDLIST_HPP__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
extern C {
int exit(int);
};
//單鏈表結點類定義
template <class T> //結點數據域data的類型以參數 (模板)形式提供
class Node {
public: //公有成員
T data; //數據域,允許外部直接訪問
private: //私有成員
Node<T> *next; //指針域(鏈域),指向后繼結點的指針
public: //公有成員
//構造函數(初始化data和next)
Node(const T& item, Node<T> *pNext=NULL) :
data(item), next(pNext){}
//在當前結點之后插入指針p所指結點
void InsertAfter(Node<T> *p) {
if (!p) return; //若p為空,則返回
p->next = next; //將待插入結點p的next指向當前結點的next域
next = p; //將當前結點的next更新為待插入結點p
}
//刪除當前結點的后繼結點并返回被刪除結點的地址
Node<T> *DeleteAfter() {
if (!next) return NULL; //若無后繼(next為NULL),則返回
Node<T> *pNext = next; //next不為空,則記錄其地址(留待函數返回后做處理)
next = next->next; //用后繼結點(next)的后繼來更改當前結點的next域
return pNext; //返回已記錄下的待刪除結點地址
}
//返回指向當前結點的后繼結點的指針
Node<T> *NextNode() const { return next; }
T GetData() const { return data; }
void SetData(const T &item) { data = item; }
};
//單鏈表類定義
template <class T>
class LinkedList {
private:
Node<T> *front, *rear; //表頭,表尾
Node<T> *currptr; //指向當前結點的指針
int size; //表長(結點的個數)
private:
//生成新結點
Node<T> *GetNode(const T& item, Node<T> *pNext = NULL) {
Node<T> *newNode;
//新分配一結點存儲空間并初始化數據成員
newNode = new Node<T>(item, pNext);
if (!newNode) {
cerr << 存儲空間分配失??!程序將終止。 << endl;
exit(1);
}
return newNode;
}
//釋放結點p
void *freeNode(Node<T> *p) { if (p) delete p; }
private:
//當鏈表為空時插入結點時的處理
int InsertNewNodeWhenListIsEmpty(const T &item) {
if (size > 0) return 0; //不為空表,返回False(0)
currptr = GetNode(item);
front = currptr;
rear = currptr;
size ++;
return 1; //在空表中插入了結點,返回True(1)
}
public:
//構造函數
LinkedList() {
front = NULL;
rear = NULL;
currptr = NULL;
size = 0;
}
//拷
- 1 回答
- 0 關注
- 135 瀏覽
添加回答
舉報