线性表
顺序表
- 此为顺序表,有表头(结构体形成)信息是表容量,表长,和int元素。
实例,head.h文件
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct _tag_SeqList { //定义头节点
int capacity; ///表容量
int length; ///表长度
int *node; ///指针
}TSeqList;
//创建顺序表
TSeqList *SeqList_Create(int capacity) {//返回SeqList *类型,即顺序表地址
int ret;
TSeqList *temp = NULL;
temp = (TSeqList*)malloc(sizeof(TSeqList));
if (temp == NULL)
{
ret = 1;
printf("func SeqList_Create()error:%d\n", ret);
return NULL;
}
memset(temp, 0, sizeof(TSeqList));
temp->capacity = capacity;
temp->length = 0;
temp->node = (int*)malloc(sizeof(void*)*capacity);//分配一个指针数组?
if (temp->node == NULL) {
ret = 2;
printf("func SeqList_Create() error:%d\n", ret);
return NULL;
}
return temp;
}
//求顺序表容量
int SeqList_Capacity(TSeqList *List)
{
return List->capacity;
}
//获取顺序表长度
int SeqList_Length(TSeqList *List)
{
return List->length;
}
//插入元素
int SeqList_Insert(TSeqList *List, int node, int pos)
{
int i;
if (List == NULL) { return -1; }
if (List->length >= List->capacity)return -2;///如果表已满。
if (pos > List->length)pos = List->length;
for (i = List->length; i > pos; i++)
{
List->node[i] = List->node[i - 1];
}
List->node[i] = node;
List->length++;
return 0;
}
//删除元素
int SeqList_Delete(TSeqList*List, int pos)
{
int value,i;
if (List == NULL || pos < 0 || pos >= List->length)
{
printf("SeqList_Delete() error\n");
return NULL;
}
value = List->node[pos];
for (i = pos + 1; i < List->length; i++)
{
List->node[i - 1] = List->node[i];
}
List->length--;
return value;
}
//查找元素
int SeqList_Get(TSeqList *List, int pos)
{
int m;
if (List == NULL || pos < 0 || pos >= List->capacity)
{
printf("SeqList_Get() error\n");
return 0;
}
m = List->node[pos];
return m;
}
//清空列表
void SeqList_Clear(TSeqList *List)
{
if (List == NULL) return;
List->length = 0;
memset(List->node, 0, (List->capacity * sizeof(void*)));//将顺序表全部归零。
return;
}
//销毁表
void SeqList_Destory(TSeqList * List)
{
if (List == NULL) return;
if (List->node != NULL) {
free(List->node);
}
free(List);
return;
}
*** main文件***
#include"linear.h"
int main()
{
int m, n;
TSeqList *List;
List = SeqList_Create(10);
SeqList_Insert(List,2, 0);
SeqList_Insert(List, 1, 3);
m = SeqList_Capacity(List);
printf("the capacity is %d\nthe value is %d\n", m,List->node[0]);
SeqList_Delete(List, 3);
n = SeqList_Length(List);
printf("the capacity is %d\nthe length is %d", m, n);
m=SeqList_Get(List, 5);
printf("\n%d", m);
SeqList_Clear(List);
printf("\nthe value is %d\n", List->node[0]);
SeqList_Destory(List);
printf("hello");
system("pause");
return 0;
}