\/*************************************************
對應教材2.4.2節, 單鏈表類LinkList的使用範例
**************************************************\/
#include \/\/引入輸入輸出流
using namespace std;
template
struct Node
{
DataType data; \/\/數據域
Node *next; \/\/指針域
};
template
class LinkList
{
public:
LinkList( ); \/\/無參構造函數,建立隻有頭結點的空鏈表
LinkList(DataType a[ ], int n); \/\/有參構造函數,建立有n個元素的單鏈表
~LinkList( ); \/\/析構函數
int Length( ); \/\/求單鏈表的長度
int Empety();
DataType Get(int i); \/\/按位查找。查找第i個結點的元素值
int Locate(DataType x); \/\/按值查找。查找值為x的元素序號
void Insert(int i, DataType x); \/\/插入操作,第i個位置插入值為x的結點
DataType Delete(int i); \/\/刪除操作,刪除第i個結點
void PrintList( ); \/\/遍
Node *p \\u003d first->next; \/\/工作指針p初始化
while (p !\\u003d nullptr)
{
cout << p->data << \\\" \\\";
p \\u003d p->next; \/\/工作指針p後移,注意不能寫作p++
}
}
template
int LinkList :: Length( )
{
Node *p \\u003d first->next; \/\/工作指針p初始化為開始接點
int count \\u003d 0; \/\/累加器count初始化
while (p !\\u003d nullptr)
{
p \\u003d p->next;
count++;
}
return count; \/\/注意count的初始化和返回值之間的關係
}
template
DataType LinkList :: Get(int i)
{
Node *p \\u003d first->next; \/\/工作指針p初始化
int count \\u003d 1; \/\/累加器count初始化
while (p !\\u003d nullptr \\u0026\\u0026 count < i)
{
p \\u003d p->next; \/\/工作指針p後移
count++;
}
if (p \\u003d\\u003d nullptr) throw \\\"位置\\\";
else return p->data;
}