循环链表可以是首尾相连,也可以是在链表的某一位置有一个loop。
循环链表示意图1.png
下面给出一个创建循环链表的函数creatCircleList
Node * creatCircleList(float *data, int totalL, int circleL){
/*
Input PARA:
float *data: the input data for list
int totalL: the total number of all nodes
int circleL: the node number of circle
*/
if(totalL<circleL || totalL < 3 || circleL<2){
printf("The total length is less than 3 or the circle length is less than 2!!!");
return(NULL);
}
//
Node *head, *end;
Node *node1;
Node *nodestc;//the position for circle start
int ii,k;
head = (Node *)malloc(sizeof(Node));
head->flag = 1;
end = head;
for(ii=0;ii<totalL-circleL;ii++){
node1 = (Node *)malloc(sizeof(Node));
node1->value = data[ii];
end->next = node1;
end = node1;
}
// the first node of circle
node1 = (Node *)malloc(sizeof(Node));
node1->value = data[ii];
end->next = node1;
end = node1;
nodestc = end;
for(k=1;k<circleL;k++){
node1 = (Node *)malloc(sizeof(Node));
node1->value = data[ii+k];
end->next = node1;
end = node1;
}
end->next = nodestc;
// return
return(head);
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
上述这个写法显得有些笨拙,也是我第一次写出来的,后来看了网上大神留下的c++代码,将过程简化:
- 创建一个单项链表,记住circle的第一个节点位置,最后将单向链表的尾节点“接到”该节点即可。
Node * creatCircleList(float *data, int totalL, int circleL){
/*
Input PARA:
float *data: the input data for list
int totalL: the total number of all nodes
int circleL: the node number of circle
*/
if(totalL<circleL || totalL < 3 || circleL<2){
printf("The total length is less than 3 or the circle length is less than 2!!!");
return(NULL);
}
//
Node *head, *end;
Node *cirnode1st_posi;// the first node of circle
Node *node1;
int ii;
head = (Node *)malloc(sizeof(Node));
head->flag = 1;
end = head;
for(ii=0;ii<totalL;ii++){
node1 = (Node *)malloc(sizeof(Node));
node1->value = data[ii];
if(ii == totalL-circleL){
cirnode1st_posi = node1;
//printf("first node of circle: %d\n",ii);
}
end->next = node1;
end = node1;
}
end->next = cirnode1st_posi;
// return
return(head);
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
网友评论