循环链表的创建 (采用为尾插法)

来源:互联网 发布:知乎怎么关注更多话题 编辑:程序博客网 时间:2024/05/16 07:46

循环链表的创建和普通单项链表的创建没有什么区别,只不过在链表尾端的指针指向链表头结点即可,没什么难度,直接上代码了啊!

#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;   }


0 0