循環鏈表的創建 (採用爲尾插法)

循環鏈表的創建和普通單項鍊表的創建沒有什麼區別,只不過在鏈表尾端的指針指向鏈表頭結點即可,沒什麼難度,直接上代碼了啊!

#include<stdio.h>
#include<stdlib.h>
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<len ;i++ )
                {
                 new_node = ( clink )malloc( sizeof(cnode) );
                    if( !new_node )
                      return NULL; 
                 /*創建結點內容設置指針處值*/
                  new_node->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;
   }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章