顺序表的感觉和理解
通讯录便用的是顺序表的结构,顺序表是将数据依次存储,形成一条线,一般要数组存储,顺序表分为静态顺序表和动态顺序表,静态该顺序表的大小已经决定好,代码运行不可更改,而动态可以通过malloc开辟,用ralloc再次分配空间
game.h
#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
typedef int SLDateType;
typedef struct SeqList
{
SLDateType* a;
int sit;
int capacity;
}SeqList;
// 对数据的管理:增删查改
void SeqListInit(SeqList* ps);
void SeqListDestroy(SeqList* ps);
void SeqListPrint(SeqList* ps);
void SeqListPushBack(SeqList* ps, SLDateType x);
void SeqListPushFront(SeqList* ps, SLDateType x);
void SeqListPopFront(SeqList* ps);
void SeqListPopBack(SeqList* ps);
// 顺序表查找
int SeqListFind(SeqList* ps, SLDateType x);
// 顺序表在pos位置插入x
void SeqListInsert(SeqList* ps, int pos, SLDateType x);
// 顺序表删除pos位置的值
void SeqListErase(SeqList* ps, int pos);
game.c
#include"game.h"
#define _CRT_SECURE_NO_WARNINGS 1
#define k sizeof(int *)
#include<string.h>
void SeqListInit(SeqList* ps)
{
ps->capacity = 5;
//最大存储量
ps->sit = 0;
ps->a= malloc(ps->capacity * k);
}
void SeqListDestroy(SeqList* ps)
{
free(ps->a);
ps->a = NULL;
}
void SeqListPrint(SeqList* ps)
{
int num;
for (num = 0; num < ps->sit; num++)
printf("%d", ps->a[num]);
printf("\n");
}
void SeqListPushBack(SeqList* ps, SLDateType x)
{
ps->a[ps->sit++] = x;
if (ps->sit == ps->capacity)
{
int* tpt = realloc(ps->a, ps->capacity * 2 * k);
if (tpt == NULL)
{
perror(realloc);
return;
}
ps->capacity *= 2;
ps->a = tpt;
}
}
void SeqListPushFront(SeqList* ps, SLDateType x)
{
memmove(ps->a + 1, ps->a, ps->sit * 4);
ps->sit++;
*ps->a = x;
if (ps->sit == ps->capacity)
{
int* tpt = realloc(ps->a, ps->capacity * 2 * k);
if (tpt == NULL)
{
perror(realloc);
return;
}
ps->capacity *= 2;
ps->a = tpt;
}
}
void SeqListPopFront(SeqList* ps)
{
assert(ps->sit);
ps->sit--;
memmove(ps->a, ps->a + 1, ps->sit * 4*1);
}
void SeqListPopBack(SeqList* ps)
{
assert(ps->sit);
ps->sit--;
}
// 顺序表查找
int SeqListFind(SeqList* ps, SLDateType x)
{
int i;
for (i = 0; i < ps->sit; i++)
{
if (ps->a[i] == x)
return i+1;
}
}
// 顺序表在pos位置插入x
void SeqListInsert(SeqList* ps, int pos, SLDateType x)
{
assert(pos>=1&&pos<=ps->sit);
memmove(ps->a + pos , ps->a + pos-1, (ps->sit - pos+1) * 4);
ps->a[pos-1] = x;
ps->sit++;
if (ps->sit == ps->capacity)
{
int* tpt = realloc(ps->a, ps->capacity * 2 * k);
if (tpt == NULL)
{
perror(realloc);
return;
}
ps->capacity *= 2;
ps->a = tpt;
}
}
// 顺序表删除pos位置的值
void SeqListErase(SeqList* ps, int pos)
{
assert(pos>=1&&pos<=ps->sit);
assert(ps->sit);
if (pos > ps->sit)
return;
memmove(ps->a + pos-1, ps->a + pos , (ps->sit - pos ) * sizeof(int));
ps->sit--;
}