循環鏈表的創建和普通單項鏈表的創建沒有什麼區別,只不過在鏈表尾端的指針指向鏈表頭結點即可,沒什麼難度,直接上代碼了啊!
#include#include struct clist { int data; struct clist *next; }; typedef struct clist cnode; typedef cnode *clink; clink createclist(int *array,int len) { clink head; clink before; clink new_node; int i; head = ( clink )malloc( sizeof(cnode) ); if( !head ) return NULL; head->data =array[0]; head->next = NULL ; before = head; for( i =1; i data =array[i]; new_node->next = NULL; /*將前結點指向新結點,新結點成為前結點*/ before->next = new_node; before = new_node; } /*創建環狀連接,返回鏈表起始指針*/ new_node->next = head; return head; } int main() { clink head; clink ptr; int list[6] = {9,7,3,4,5,6}; int i = 0; head = createclist(list,6); if( head == NULL) { printf("內存分配失敗!"); exit(1); } printf("數組內容:"); for( i = 0; i < 6;i++) printf("[%d]",list[i]); printf("\n鏈表內容為:"); ptr = head; do { printf("%d",ptr->data); ptr=ptr->next; }while( head != ptr ); printf("\n"); return 0; }