帶表頭的單迴圈鍊錶的實現

2021-07-03 14:44:49 字數 2222 閱讀 2909

通常在迴圈鍊錶的第乙個節點前附加乙個特殊的節點來作為標記,這個節點稱為迴圈鍊錶的頭結點,頭結點的資料域為空域,或者按照需要設定。

在這裡,我們將a1節點的位址設為first,頭結點僅當作特殊標記。如果不想增加頭結點,也可以實現單迴圈鍊錶。

本篇的單迴圈鍊錶是根據上篇《單鏈表的實現》上稍作修改而來,有什麼好的建議請指點我!

1.標頭檔案

#ifndef chain_h

#define chain_h

#include//帶頭節點的迴圈鍊錶,頭結點是空表

templateclass chainnode

~chainnode()

void setdata(const t& dat)

public:

t getdata()

chainnode* getnext()

private:

t data;

chainnode* next;

};templateclass chain

~chain()

delete head;

}public:

bool isempty() //當迴圈鍊錶中只存在表頭的時候,為空

chainnode* getfirst()

chainnode* gethead()

void deletenode(int pos);

int getlength();

void insertbefore(t dat, int pos);

void insertafter(t dat, int pos);

t find(int pos);

private:

chainnode* first; //指向第乙個有意義的節點

chainnode* head; //頭結點,特殊標記

int length;

};templatevoid chain::insertbefore(t dat, int pos) //在pos位置前面插入乙個元素

chainnode* now = new chainnode < t >;

now->data = dat;

if (first == nullptr) //如果迴圈鍊錶只有表頭,為空表

else

else

++length;

} }}templatevoid chain::insertafter(t dat, int pos)

chainnode* now = new chainnode < t >;

now->data = dat;

if (first == nullptr)

else

else

++length;

} }}templatet chain::find(int pos)

chainnode* curr=first;

for (int i = 1; i < pos; ++i)

curr = curr->next;

return curr->data; }}

templateint chain::getlength()

length = len;

return len;

}templatevoid chain::deletenode(int pos)

if (pos == 1)

else

} }}

templatestd::ostream& operator <

std::cout << std::endl;

return out;

}#endif

2.main檔案

#include#include"chain.h"

using namespace std;

int main()

cout << endl;

//*********這段**目的只為測試********

auto dd = liner.find(3);

cout << dd << endl;

cout<< liner << endl;

system("pause");

return 0;

}

帶表頭結點的雙向迴圈鍊錶

include include 定義鍊錶資料結構 struct node typedef struct node node typedef struct node link 功能 設頭結點 返回 void void creat link link head head next head head p...

帶表頭結點的雙向迴圈鍊錶

include include 定義鍊錶資料結構 struct node typedef struct node node typedef struct node link 功能 設頭結點 返回 void void creat link link head head next head head p...

單迴圈鍊錶

頭插 尾插 顯示 頭刪 尾刪 按值插入 按位置插入 查詢 長度 逆序 清除 摧毀 初始化 排序 按位置刪除 按值刪除 可以進一步優化 ifndef sclist h define sclist h include typedef int elementtype typedef enum bool 鍊...