以下的C++類LinkList實(shí)現(xiàn)了線性鏈表的一般操作??梢灾苯釉谄渌某绦蛑兄苯咏⑺膶ο?,其中線性表中的數(shù)據(jù)在此為整型,具體應(yīng)用的時(shí)候可以適當(dāng)?shù)男薷模⒖梢栽诖嘶A(chǔ)上繼續(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();
}
}
//初始化,分配一個(gè)頭節(jié)點(diǎn)。
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();
}
}
//初始化,分配一個(gè)頭節(jié)點(diǎn)。
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。