线性表的增删查改等的实现

线性表的增删查改等的实现

#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

// 对数据的管理:增删查改 
typedef int SLDateType;
typedef struct SeqList
{
    SLDateType* date;
    size_t size;
    size_t capacity; // unsigned int
}SeqList;
//检查顺序表容量大小,是否增容
void CheckCapacity(SeqList* ps)
{
    if (ps == NULL) return;
    if (ps->size == ps->capacity)
    {
        int newCapacity = ps->capacity == 0 ? 1 : 2 * ps->capacity;
        SLDateType* tmp =(SLDateType*)malloc(sizeof(SLDateType)*newCapacity);
        memcpy(tmp, ps->date, sizeof(SLDateType)*ps->size);
        free(ps->date);
        ps->date = tmp;
        //int newCapacity = ps->capacity == 0 ? 1 : 2 * ps->capacity;
        //ps->date = (SLDateType*)relloc(ps->date,sizeof(SLDateType)*newCapacity);

        ps->capacity = newCapacity;
    }
}
//顺序表的初始化
void SeqListInit(SeqList* ps)
{
    ps->date = NULL;
    ps->size = ps->capacity = 0;
}
//顺序表的销毁,对所以指针进行释放和对传入值的date赋NULL;
void SeqListDestory(SeqList* ps)
{
    if (ps)
    {
        if (ps->date)
        {
            free(ps->date);
            ps->date = NULL;
        }
    }
}
//顺序表的打印
void SeqListPrint(SeqList* ps)
{
    for (int i = 0; i < ps->size; i++)
    {
        printf("%d", ps->date[i]);
    }
    printf("\n");
}
//顺序表的尾插
void SeqListPushBack(SeqList* ps, SLDateType x)
{
    if (ps == NULL)return;
    CheckCapacity(ps);
    ps->date[ps->size] = x;
    ps->size++;
}
顺序表的头插
void SeqListPushFront(SeqList* ps, SLDateType x)
{
    if (ps == NULL)
        return;
    CheckCapacity(ps);
    int end = ps->size;
    while (end > 0)
    {
        ps->date[end]=ps->date[end-1];
        --end;
    }
    ps->date[0] = x;
    ps->size++;
}
//顺序表的头删
void SeqListPopFront(SeqList* ps)//头删
{
    if (ps == NULL||ps->size==0) return;
    int i = 1;
    while (i < ps->size)
    {
        ps->date[i-1] = ps->date[i]; i++;
    }
    --ps->size;
}
//顺序表的尾删
void SeqListPopBack(SeqList* ps) 
{
    if (ps == NULL)
        return;
    if (ps->size > 0)
        ps->size--;
}

// 顺序表查找
int SeqListFind(SeqList* ps, SLDateType x)
{
    if (ps == NULL)return;
    for (int i = 0; i < ps->size; i++)
    {
        if (ps->date[i] == x)return i;
    }
    return -1;

}
// 顺序表在pos位置插入x
void SeqListInsert(SeqList* ps, size_t pos, SLDateType x)
{
    if (ps == NULL)return;
    if (pos >= 0 && pos <= ps->size)
    {
        CheckCapacity(ps);
        int end = ps->size;
        while (end > pos)
        {
            ps->date[end] = ps->date[end - 1]; end--;
        }
        ps->date[end - 1] = x;
        ps->size++;

    }
}
// 顺序表删除pos位置的值
void SeqListErase(SeqList* ps, size_t pos)
{
    //
    if (ps == NULL || ps->size == 0)return;
    if (pos >= 0 && pos < ps->size)
    {
    //赋值
        int i = pos;
        while (i<ps->size-1)
        {
            ps->date[i] = ps->date[i+1]; i++;
        }
    }
    //更新
    ps->size--;
}

猜你喜欢

转载自blog.51cto.com/14982125/2562884