線性表的增刪查改等的實現

線性表的增刪查改等的實現

#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--;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章