以下的C++類LinkList實現(xiàn)了線性鏈表的一般操作??梢灾苯釉谄渌某绦蛑兄苯咏⑺膶ο螅渲芯€性表中的數據在此為整型,具體應用的時候可以適當的修改,并可以在此基礎上繼續(xù)封裝特定的功能。
頭文件:LinkList.h
typedef struct LNode {
int data;
struct LNode *next;
}LNode, *pLinkList;
class LinkList {
private:
pLinkList m_pList;
int m_listLength;
public:
LinkList();
~LinkList();
bool InitList ();
bool DestroyList ();
bool ClearList();
bool IsEmpty ();
int GetLength ();
bool GetNode(int position, LNode** node);
int LocateElem(int elem);
bool SetNodeData(int position, int newData);
bool GetNodeData(int position, int &data);
bool InsertNode(int beforeWhich, int data);
bool DeleteNode(int position);
};
Cpp文件:LinkList.cpp
#include
#include "LinkList.h"
LinkList::LinkList() {
m_pList = NULL;
m_listLength = 0;
InitList();
}
LinkList::~LinkList() {
if (!DestroyList()) {
DestroyList();
}
}
//初始化,分配一個頭節(jié)點。
bool LinkList::InitList() {
if (!(m_pList = new LNode)) {
return false;
}
m_pList->next = NULL;
return true;
}
//銷毀鏈表。
bool LinkList::DestroyList() {
if (!ClearList()) {
return false;
}
delete m_pList;
return true;
}
//判斷鏈表是否為空。若為空,返回true,否則返回false。
頭文件:LinkList.h
typedef struct LNode {
int data;
struct LNode *next;
}LNode, *pLinkList;
class LinkList {
private:
pLinkList m_pList;
int m_listLength;
public:
LinkList();
~LinkList();
bool InitList ();
bool DestroyList ();
bool ClearList();
bool IsEmpty ();
int GetLength ();
bool GetNode(int position, LNode** node);
int LocateElem(int elem);
bool SetNodeData(int position, int newData);
bool GetNodeData(int position, int &data);
bool InsertNode(int beforeWhich, int data);
bool DeleteNode(int position);
};
Cpp文件:LinkList.cpp
#include
#include "LinkList.h"
LinkList::LinkList() {
m_pList = NULL;
m_listLength = 0;
InitList();
}
LinkList::~LinkList() {
if (!DestroyList()) {
DestroyList();
}
}
//初始化,分配一個頭節(jié)點。
bool LinkList::InitList() {
if (!(m_pList = new LNode)) {
return false;
}
m_pList->next = NULL;
return true;
}
//銷毀鏈表。
bool LinkList::DestroyList() {
if (!ClearList()) {
return false;
}
delete m_pList;
return true;
}
//判斷鏈表是否為空。若為空,返回true,否則返回false。