C语言-循环链表

循环链表可以是首尾相连,也可以是在链表的某一位置有一个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++代码,将过程简化:

  1. 创建一个单项链表,记住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);
    }
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容