循環鏈表的插入、刪除
循環鏈表的插入示意:
循環鏈表的刪除示意:
typedef void CircleList;
typedef struct _tag_CircleListNode
{
struct _tag_CircleListNode * next;
}CircleListNode;
typedef struct _tag_CircleList
{
CircleListNode header;
CircleListNode* slider;
int length;
}TCircleList;
//插入,對應第一幅示意圖
int CircleList_insert(CircleList* list, CireListNode* node, int pos)
{
int ret = 0, i=0;
TCircleList* sList = (TCircleList*)list;
if (list == NULL || node== NULL || pos<0)
{
return -1;
}
CircleListNode* current = (CircleListNode*)sList;
for(i=0; (i<pos) && (current->next != NULL); i++)
{
current = current->next;
}
//current->next 0號節點的地址
node->next = current->next; //1
current->next = node; //2
//若第一次插入節點
if( sList->length == 0 )
{
sList->slider = node;
}
sList->length++;
//若頭插法 current仍然指向頭部
//(原因是:跳0步,沒有跳走) 中間第一種情況
if( current == (CircleListNode*)sList )
{
//獲取最後一個元素
CircleListNode* last = CircleList_Get(sList, sList->length - 1);
last->next = current->next; //3
}
return ret;
}
CircleListNode* CircleList_Get(CircleList* list, int pos) // O(n)
{
TCircleList* sList = (TCircleList*)list;
CircleListNode* ret = NULL;
int i = 0;
if (list==NULL || pos<0)
{
return NULL;
}
{
CircleListNode* current = (CircleListNode*)sList;
for(i=0; i<pos; i++)
{
current = current->next;
}
ret = current->next;
}
return ret;
}
//刪除,對應第二幅圖
CircleListNode* CircleList_Delete(CircleList* list, int pos) // O(n)
{
TCircleList* sList = (TCircleList*)list;
CircleListNode* ret = NULL;
int i = 0;
if( (sList != NULL) && (pos >= 0) && (sList->length > 0) )
{
CircleListNode* current = (CircleListNode*)sList;
CircleListNode* last = NULL;
for(i=0; i<pos; i++)
{
current = current->next;
}
//若刪除第一個元素(頭結點)左上
if( current == (CircleListNode*)sList )
{
last = (CircleListNode*)CircleList_Get(sList, sList->length - 1);
}
//求要刪除的元素 右上 左上
ret = current->next;
current->next = ret->next;
sList->length--;
//判斷鏈表是否爲空
if( last != NULL )
{
sList->header.next = ret->next;
last->next = ret->next;
}
//若刪除的元素爲遊標所指的元素
if( sList->slider == ret )
{
sList->slider = ret->next;
}
//若刪除元素後,鏈表長度爲0
if( sList->length == 0 )
{
sList->header.next = NULL;
sList->slider = NULL;
}
}
return ret;
}
總結
循環鏈表的插入:注意第一次插入的條件判斷(維護遊標);只有一個頭結點的插入;
循環鏈表的刪除:注意刪除第一個元素(頭結點);current->next = current->next->next;不需要考慮鏈表是否爲空,而last->next = ret->next;需要考慮,即爲第一個節點的刪除。