0x00数据结构——C语言实现(单向循环链表)
#ifndef CIRCULAR_LIST
#define CIRCULAR_LIST
typedef int T;
#define MAXLEN 100
typedef enum {
false = 0,
true
} BOOL;
struct node;
typedef struct node cnode;
typedef struct node *to_node;
typedef to_node c_list;
typedef to_node pos;
c_list create_list(void);
BOOL set_empty(c_list l);
int calc_length(c_list l);
pos head_addr(c_list l);
pos search(c_list l, T x);
pos locate(c_list l, int i);
T get_val(c_list l, int i);
BOOL change_val(c_list l, int i, const T x);
BOOL insert_val(c_list l, int i, const T x);
BOOL delete_val(c_list l, int i, T *x);
BOOL isempty(c_list l);
void output(c_list l);
BOOL sort(c_list l);
#endif
#include <stdio.h>
#include <stdlib.h>
#include "circular_list.h"
struct node{
T val;
struct node *next;
};
c_list create_list(void)
{
c_list l = (c_list)malloc(sizeof(cnode));
l->next = l;
l->val = 0;
return l;
}
BOOL set_empty(c_list l)
{
pos tmp = l->next, ttemp;
while(tmp!=l){
ttemp = tmp->next;
free(tmp);
tmp = ttemp;
}
l->next = l;
l->val = 0;
return true;
}
int calc_val(c_list l)
{
return l->val;
}
pos head_addr(c_list l)
{
return l;
}
pos search(c_list l, T x)
{
int i = 1;
pos tmp;
tmp = l->next;
while(tmp != l && tmp->val != x && i<=l->val){
tmp = tmp->next;
i++;
}
if(i>l->val) return NULL;
else return tmp;
}
pos locate(c_list l, int i)
{
if(i<=l->val && i>0){
pos tmp;
tmp = l;
while(--i>=0){
tmp = tmp->next;
if(tmp == l) break;
}
return tmp;
} else {
printf("can not access the %d'th element\n", i);
return NULL;
}
}
T get_val(const c_list l, int i)
{
if(i<=l->val && i>0){
pos tmp;
tmp = l;
while(--i>=0){
tmp = tmp->next;
if(tmp == l) break;
}
return tmp->val;
} else {
printf("can not access the %d'th element\n", i);
return -1;
}
}
BOOL change_val(c_list l, int i, const T x)
{
if(i<=l->val && i>0){
pos tmp;
tmp = l;
while(--i>=0){
tmp = tmp->next;
if(tmp == l) break;
}
tmp->val = x;
return true;
} else {
return false;
}
}
BOOL insert_val(c_list l, int i, const T x)
{
if(i<=l->val && i>=0){
pos tmp;
tmp = l;
while(--i>=0){
tmp = tmp->next;
if(tmp == l) break;
}
to_node t = (to_node)malloc(sizeof(cnode));
t->next = tmp->next;
t->val = x;
tmp->next = t;
l->val++;
return true;
} else {
return false;
}
}
BOOL delete_val(c_list l, int i, T *x)
{
if(i<=l->val && i>0){
i--;
pos tmp;
tmp = l;
while(--i>=0){
tmp = tmp->next;
if(tmp == l) break;
}
*x = (tmp->next)->val;
tmp->next = (tmp->next)->next;
l->val--;
return true;
} else {
return false;
}
}
BOOL isempty(const c_list l)
{
return (l->val == 0 ? true:false);
}
void output(const c_list l)
{
pos tmp = NULL;
int i = 1;
tmp = l->next;
while(tmp!=l){
printf("the %dth element is %d\n", i++, tmp->val);
tmp = tmp->next;
}
}
BOOL sort(const c_list l)
{
if(l->val < 2) {
return true;
}
pos tmp, tmp1, tmp2;
int i;
tmp = l->next;
while(tmp->next != l) {
tmp1 = l->next;
tmp2 = tmp1->next;
while(tmp2 != l) {
if(tmp1->val > tmp2->val) {
i = tmp1->val;
tmp1->val = tmp2->val;
tmp2->val = i;
}
tmp1 = tmp1->next;
tmp2 = tmp2->next;
}
tmp = tmp->next;
}
return true;
}