循环链表的重点在于尾节点的指针重新指向了头节点,节点的定义与单向链表中的定义无异:
struct Node
{
int data; //节点的数据
struct Node *next; //保存下一个节点的地址
};
头节点的创建与单向链表不同
struct Node * loop_list_init()
{
struct Node * head=(struct Node*)malloc(sizeof(struct Node*));
head->data=0;
head->next=head; //注意这里头节点指向自己
return head;
}
一、循环链表的插入:循环链表同样有头插法和尾插法
1.头插法:循环链表的头插法,在代码实现上与单向链表相同
void lpHeadInsert(struct Node* list,int data)
{
struct Node* temp=(struct Node*)malloc(sizeof(struct Node*));
temp->data=data;
temp->next=list->next;
list->next=temp;
}
2.尾插法:遍历到尾节点之后添加节点
void lpTailInsert(struct Node* list,int data)
{
struct Node* temp=(struct Node*)malloc(sizeof(struct Node*));
temp->data=data;
struct Node* ergodic=list->next;
while(ergodic->next!=list) //遍历到最后一个节点
ergodic=ergodic->next;
temp->next=ergodic->next;
ergodic->next=temp;
}
二、循环链表的遍历:注意控制循环停止的条件
void print(struct Node* list)
{
struct Node* temp=list->next;
printf("loop list: ");
while(temp!=list)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
三、循环链表的删除
void lpListDelete(struct Node* list,int data)
{
struct Node* pre=list;
struct Node* del=pre->next;
while(del!=list)
{
if(data==del->data)
{
pre->next=del->next;
}
pre=del;
del=del->next;
}
}
写这个lpListDelete函数的时候总是段错误,后来去看了一下发现我把del给释放了,在此记录,防止再犯此类错误。循环列表中由于没有free(del)使得删除了重复的两个5,所以我之前的单向链表是否也可以通过不做free从而达到目的呢。