循环链表的结束条件为p == list.pHead
#include <stdio.h>
//链表结点
typedef struct ListNode
{
int val;
struct ListNode *pNext;
}ListNode;
//链表头
typedef struct List
{
int length;
ListNode *pHead;
}List;
//初始化
void init(List &list)
{
list.length = 0;
list.pHead = NULL;
}
//销毁链表
void destroy(List &list)
{
ListNode *p = list.pHead, *pNext = NULL;
while(NULL != p)
{
do
{
pNext = p->pNext;
delete p;
p = pNext;
}while(p != list.pHead);
//判断条件:若当前结点等于头结点,说明链表走了一圈,结束了。
}
list.length = 0;
list.pHead = NULL;
}
int mod(List &list, int index)
{
//把索引位置映射为可索引位置
return (list.length == 0) ? 0 : index % list.length;
}
//获得索引处的结点
ListNode *getNode(List &list, int index)
{
ListNode *p = NULL;//若index<0,则返回NULL;
if(index >= 0)
{
index = mod(list, index);//总有可索引index
int i = 0;
p = list.pHead;
while(i != index)
<