19_1.20线性表

线性表

顺序表

  1. 此为顺序表,有表头(结构体形成)信息是表容量,表长,和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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值