循环单链表的c语言实现

 1 /**
 2  * 循环单链表的实现
 3  */
 4 #include <stdio.h>
 5 #include <stdlib.h>
 6 
 7 typedef struct List {
 8     int data;
 9     struct List *pNext;
10 } *List;
11 
12 /**
13  * 初始化一个头节点然后用一个局部变量来连接新节点和头部
14  * 最后局部变量将尾节点接至头节点
15  * @param num创建数量
16  * @return 头节点
17  */
18 List init(int num) {
19     List head = (List *) malloc(sizeof(List));
20     head->data = 0;
21     head->pNext = NULL;
22     List cycle = head;
23 
24     for (int i = 1; i <= num; ++i) {
25         List body = (List *) malloc(sizeof(List));
26         body->data = i;
27         body->pNext = NULL;
28         cycle->pNext = body;
29         cycle = cycle->pNext;
30     }
31     cycle->pNext = head;
32     return head;
33 }
34 
35 void print(List L) {
36     List temp;
37     temp = L;
38     while (temp->pNext != L) {
39         printf("%d", temp->data);
40         temp = temp->pNext;
41     }
42 }
43 
44 int main() {
45     List L;
46     L = init(8);
47     print(L);
48     return 0;
49 }

 

posted @ 2021-08-31 17:06  新生代农民工  阅读(72)  评论(0)    收藏  举报