数据结构之存储结构

线性表(List):零个或多个数据源数的有限序列。

  • 顺序存储结构
  • 链式存储结构  :  单链表、静态链表、双向链表、循环链表

一、顺序存储结构

typedef void List_Node;     //用于复用加入元素

typedef unsigned long Seqlist_Node;   //为了重复使用,所以在这里使用的地址来操作的, 这里要用unsigned long类型,unsingesd int类型是在32位系统下使用的

typedef struct  //存储线性表的结构体
{
   	int MAXSIZE; //线性表最大存储
	int length;  //线性表当前存储大小
	Seqlist_Node* node;  //指向下一个元素的地址,这样做的好处是能动态的申请数组,如果不这样,这里是数组
}Tseqlist;

创建和销毁函数:

Tseqlist* List_Create(int MAXSIZE)   //创建线性表
{
	Tseqlist* list  = NULL;
	if(MAXSIZE > 0)
	{
		list = (Tseqlist*)malloc( sizeof(Tseqlist) + sizeof(Seqlist_Node)*MAXSIZE );
	}
	if(list != NULL)
	{
		list->MAXSIZE = MAXSIZE;
		list->length = 0;
		list->node = (Seqlist_Node*)(list + 1);  //node指向下一个结构体元素的首地址
	}
	return list;
}

void List_Destroy(Tseqlist* list)  //销毁线性表
{
	free(list);
}

二、链式存储结构

1、单链表(在代码中List_Node是结构体类型,代码将索要存放的值作为node结构体的首地址)

typedef struct __List_Node List_Node;

typedef struct __List_Node   //节点指针域定义
{
	List_Node* next;
}List_Node;

typedef struct Linklist    //头结点定义
{
	List_Node header;       //头节点指针域
	int length;           //链表长度
}Linklist;

typedef struct           //数据域
{
	List_Node header;
	int v;               //需要存储的数据
}List_NodeData;

创建、插入和销毁函数:

Linklist* List_Create()     //创建线性表
{
	Linklist* ret = (Linklist*)malloc(sizeof(Linklist));
	if( ret != NULL )
	{
		ret->header.next = NULL;
		ret->length = 0;
	}
	return ret;
}

void List_Destroy(Linklist* list)     //销毁线性表
{
	free(list);
}

int List_Insert(Linklist* list, List_Node* node, int pos)    //将元素插入到线性表中
{
	int flag = (list != NULL) && (0 <= pos) && (node != NULL);
	List_Node* current = (List_Node*)list;
	if(flag)
	{
		int i;
		for(i = 0; (i<pos) &&(current->next != NULL); i++)
			current = current->next;
		node->next = current->next;
		current->next = node;
		list->length++;
	}
	return flag;
}
 
 
List_Node* List_Get(Linklist* list, int pos)    //获取元素
{
	int flag = (list != NULL) && (0 <= pos) && (pos < list->length);
	List_Node* ret = NULL;
	if(flag)
	{
		List_Node* current = (List_Node*)list;
		int i;
		for(i = 0; (i<pos) &&(current->next != NULL); i++)
			current = current->next;
		ret = current->next;
	}
	return ret;
}
int main()
{
	Tseqlist* list = List_Create(5);
	int q = 9;
	int w = 8;
	int e = 5;
	int r = 2;
	int t = 0;
	List_Insert(list, &q, 0);
	List_Insert(list, &w, 0);
	List_Insert(list, &e, 0);
	List_Insert(list, &r, 0);
	List_Insert(list, &t, 0);
	int i = 0;
	for(i = 0; i<List_Length(list); i++)
	{
		int* a = (int*) List_Get(list, i);
		printf("%d\n", *a);
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_31820761/article/details/80684673