循环链表:
#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;
}
void main()
{
clink head;
clink ptr; //输出用链表指针
int list[6] = {9,7,3,4,5,6};
int i;
head = createclist(list,6);
if (head == NULL)
{
printf("内存分配失败/n");
exit(1);
}
printf(“数组内容: ”);
for( i= 0;i<6;i++)
printf(“[%d],list[i]”);
pirntf(“/n链表内容: ”);
ptr = head; //指向链表开始
do
{
Printf(“[%d],ptr->data”);
Ptr = ptr->next;
}while (head != ptr);
Printf(“/n”);
}