循环链表和单链表其实区别不大,差别仅在于算法中的循环条件不是p或者p->next,而是是否等于头指针。下面这个例子简单的实现了循环链表的基本操作,其中插入和删除只是完成了主要的部分,没有判断。
#include
#include
struct Data
{
char name;
int age;
};
struct CirList
{
Data *data;
CirList *next;
};
CirList* InitListhead()
{
CirList *list;
list = (CirList*)malloc(sizeof(CirList));
list->next = NULL;
return list;
}
CirList *CreateData()
{
CirList *node;
node = (CirList*)malloc(sizeof(CirList));
node->next = NULL;
node->data = (Data*)malloc(sizeof(Data));
printf("输入姓名:");
scanf("%c",&node->data->name);
printf("输入年龄:");
scanf("%d",&node->data->age);
getchar();
return node;
}
//头插法初始化链表
void InitList(CirList *head)
{
CirList *node ;
node = CreateData();
//新结点的next指针域赋给头结点的next指针域
node->next = head->next;
//新结点赋给头结点的指针域
head->next = node;
//新结点指针域指向头结点
node->next = head;
}
//尾插法初始化链表
void InitList_2(CirList *list)
{
CirList *node,*p=list;
int i = 0;
while(i<3)
{
node = CreateData();
p->next = node;
p = node;
i++;
}
//令表尾指针指向头结点
node->next = list;
}
void Insert(CirList *list)
{
CirList *node,*saveHead = list;
node = CreateData();
printf("输入插入位置:");
int position,i=0;
scanf("%d",&position);
//寻找插入的前驱
while(list != NULL && i < position-1)
{
list = list->next;
i++;
}
node->next = list->next;
list->next = node;
}
void Delete(CirList *list)
{
CirList *temp,*saveHead = list;;
printf("输入删除位置:");
int position,i=0;
scanf("%d",&position);
//寻找插入的前驱
while(list != NULL && i < position-1)
{
list = list->next;
i++;
}
temp = list->next;
list->next = temp->next;
free(temp);
}
void Output(CirList *list)
{
CirList *p = list->next;
printf("链表中所有数据如下:\n");
while(p != list)
{
printf("姓名:%c\n",p->data->name);
printf("年龄:%d\n",p->data->age);
p = p->next;
}
}
void menu()
{
printf("*****循环链表练习*****\n");
printf(" * 1---初始化链表\n");
printf(" * 2---删除数据\n");
printf(" * 3---插入数据\n");
printf(" * 4---输出数据\n");
printf(" * 0---退出\n");
printf("********************\n");
}
int main()
{
CirList *list;
list = InitListhead();
int i=0;
printf("初始化数据:\n");
//while(i<3)
{
//InitList(list);
//i++;
}
int choose;
do
{
menu();
printf("输入您的选择:");
scanf("%d",&choose);
getchar();
switch(choose)
{
case 1:
InitList_2(list);
break;
case 2:
Delete(list);
break;
case 3:
Insert(list);
break;
case 4:
Output(list);
break;
}
}while(choose !=0);
return 0;
}