循環鏈表定義
定義與單鏈表一樣,操作時將末結點的指針指向開始結點即可
typedef struct _LinkNode
{
int data;
struct _LinkNode *next;
}LinkList;
循環鏈表操作
初始化循環鏈表
bool InitList(LinkList* &L)
{
L = new LinkList;
if(!L) return false;
L->next = L;
L->data = 0; //往頭結點塞個數據,這時候嚴格來講為無頭結點循環鏈表,第一個結點應該叫開始結點
return true;
}
插入(尾插)
bool ListInsert_back(LinkList* &L, LinkList *node)
{
LinkList *last = NULL;
if(!L || !node) return false;
if(L == L->next)
{
//頭結點指針指向了自己(鏈表只有頭結點)
node->next = L;
L->next = node;
}else{
//非空的循環鏈表
last = L->next;
//尋找尾結點(指向頭結點的結點)
while(last->next != L)
{
last = last->next;
}
node->next = L;
last->next = node;
}
return true;
}
輸出數據
void LinkListPrint(LinkList *L)
{
LinkList *p;
if(!L || L == L->next)
{
cout << "鏈表為空\n";
return;
}
p = L->next;
while(p != L)
{
cout << p->data << "\t";
p = p->next;
}
cout << endl;
}