首页 > 代码库 > 04 循环链表

04 循环链表

循环链表

技术分享

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 
  5 // 数据结构
  6 typedef struct node
  7 {
  8     int data;
  9     struct node *next;
 10 }loopList;
 11 
 12 loopList *loopList_init(void)
 13 {
 14     loopList *list = (loopList *)malloc(sizeof(loopList));
 15 
 16     if (list == NULL)
 17     {
 18         return NULL; 
 19     }
 20 
 21     list->next = list;
 22 
 23     return list;
 24 }
 25 
 26 int loopList_add_head(loopList *list, int data)
 27 {
 28     if (list == NULL)
 29     {
 30         return -1;
 31     }
 32 
 33     loopList *node = (loopList *)malloc(sizeof(loopList));
 34     if (node == NULL)
 35     {
 36         return -2; 
 37     }
 38     node->data =http://www.mamicode.com/ data;
 39     node->next = list->next;
 40     list->next = node;
 41 
 42     return 0;
 43 }
 44 
 45 int loopList_del_head(loopList *list, loopList **node)
 46 {
 47     if (list == NULL || list->next == list)
 48     {
 49         return -1;
 50     }
 51 
 52     *node = list->next;
 53     list->next = list->next->next;
 54     (*node)->next = NULL;
 55 
 56     return 0;
 57 }
 58 
 59 int loopList_printf(loopList *list)
 60 {
 61     if (list == NULL)
 62     {
 63         return -1;
 64     }
 65 
 66     loopList *tmp = list->next;
 67     while (tmp != list)
 68     {
 69         printf("%d-", tmp->data); 
 70         tmp = tmp->next;
 71     }
 72     printf("\n");
 73 
 74     return 0;
 75 }
 76 
 77 int main(void)
 78 {
 79     int i = 0;
 80     loopList *list = NULL;
 81     loopList *node = NULL;
 82 
 83     list = loopList_init();
 84 
 85     for (i = 0; i < 10; i++)
 86     {
 87         loopList_add_head(list, i);
 88     }
 89 
 90     loopList_printf(list);
 91 
 92     loopList_del_head(list, &node);
 93     printf("node:%d\n", node->data);
 94     free(node);
 95     node = NULL;
 96 
 97     loopList_printf(list);
 98 
 99     return 0;
100 }

 

04 循环链表