链表 -- 环链表 环链表的创建4 node_t *clinklist_create(void) 5 { 6 node_t*pheadmalloc(sizeof(node_t)); 7 if(pheadNULL) 8 { 9 printf(malloc fail); 10 return NULL; 11 } 12 phead-nextphead; 13 return phead; 14 }与普通链表区分这里头节点指向自己环链表的头插入16 void clinlist_insert_head(node_t*phead,data_t d) 17 { 18 node_t*p_newmalloc(sizeof(node_t)); 19 if(pheadNULL) 20 { 21 printf(malloc fail); 22 return ; 23 } 24 if(phead-nextphead) //只有头节点的情况 25 { 26 phead-nextp_new; 27 p_new-nextp_new; 28 p_new-datad; 29 return; 30 } 31 node_t*p_tailphead-next; 32 while(p_tail-next!phead-next) //其实也可以处理空链表的情况下面是通用逻辑 33 p_tailp_tail-next; 34 p_tail-nextp_new; 35 p_new-nextphead-next; 36 phead-nextp_new; 37 p_new-datad; 38 return; 39 }这里采用的是头节点没有有效数据头节点不参与环的插入方法若头节点插入环实现起来会相对简单打印环链表41 void clinklist_printf(node_t*phead) 42 { 43 if(pheadNULL) 44 return; 45 node_t*pphead-next; 46 if(pphead) 47 return; 48 if(p-nextp) 49 { 50 printf(%d ,p-data); //此处特殊处理除了头节点只有一个节点的情况下面的通用逻辑也是可以处理的 51 return; 52 } 53 printf(%d ,p-data); 54 pp-next; 55 while(p!phead-next) 56 { 57 printf(%d ,p-data); 58 pp-next; 59 } 60 return; 61 }以头节点指向的首节点作为截止标志来作为结束条件环链表的查找63 node_t* clinklist_find_key(node_t*phead,data_t key) 64 { 65 node_t*pphead-next; 66 if(pphead) 67 return NULL; 68 if(p-datakey) 69 return p; 70 pp-next; 71 while(p-data!key p!phead-next) 72 pp-next; 73 if(p-datakey) 74 return p; 75 return NULL; 76 }环链表的尾删除78 void clinklist_del_tail(node_t*phead) //删除的是头结点指向的首节点的前一个节点 79 { 80 if(pheadNULL || phead-nextphead) 81 return; 82 node_t*pphead-next; 83 while(p-next-next!phead-next) 84 pp-next; 85 node_t*p_delp-next; 86 if(phead-nextp_del) //避免单节点情况下头结点的悬空指针 87 phead-nextphead; 88 p-nextphead-next; 89 free(p_del); 90 }环链表的头删除92 void clinklist_del_head(node_t*phead) 93 { 94 if(pheadNULL || phead-nextphead) 95 return; 96 node_t*p_tailphead-next; 97 while(p_tail-next ! phead-next) 98 { 99 p_tailp_tail-next; 100 } 101 node_t*p_delphead-next; 102 phead-nextp_del-next; 103 p_tail-nextp_del-next; 104 free(p_del); 105 }环链表的销毁107 void clinklist_destroy(node_t**phead) 108 { 109 if(pheadNULL || *pheadNULL) 110 return; 111 if((*phead)-next*phead) 112 { 113 free(*phead); 114 *pheadNULL; 115 return; 116 } 117 if((*phead)-next(*phead)-next-next) 118 { 119 free((*phead)-next); 120 free(*phead); 121 *pheadNULL; 122 return; 123 } 124 node_t*p(*phead)-next-next; 125 node_t*p_del(*phead)-next-next; 126 while(p!(*phead)-next) 127 { 128 pp_del-next; 129 free(p_del); 130 p_delp; 131 } 132 free(p); 133 free(*phead); 134 *pheadNULL; 135 }