一、线性表
逻辑结构为线性的数据结构称为线性表,包括:线性表 链表 字符串 栈 队列 双端队列 等等。逻辑结构接续:是想象出来的;物理结构连续:是内存连续
二、顺序表
顺序表可以看作是一个可变长的数组。
优点:
1.支持下标随机访问,有利于排序,二分查找等算法
2.缓存命中率比较高
缺点:
1.头插头删或者中部删除插入效率低O(N)
2.扩容需要一定的消耗,浪费空间
三、顺序表的实现
函数生声明:
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int SLDataType;
typedef struct SeqList {
SLDataType* a;
int size;
int capacity;
}SeqList;
void SeqListInite(SeqList* ps);
void SeqListDestory(SeqList* ps);
void SeqListPushBack(SeqList* ps, SLDataType x);
void SeqListPushFront(SeqList* ps, SLDataType x);
void SeqListPopBack(SeqList* ps);
void SeqListPopFront(SeqList* ps);
void SeqListInsert(SeqList* ps, int pos, SLDataType x);
void SeqListErase(SeqList* ps, SLDataType x);
void SeqListPrint(SeqList* ps);
void SeqListBubbleSort(SeqList* ps);
int SeqListBinarySearch(SeqList* ps, SLDataType x);
函数实现:
#include "SeqList.h"
void SeqListInite(SeqList* ps) {
ps->a = (SLDataType*)malloc(sizeof(int) * 4);
if (ps->a == NULL) {
printf("fial!");
exit(-1);
}
ps->size = 0;
ps->capacity = 4;
}
void SeqListDestory(SeqList* ps) {
free(ps->a);
ps->a = NULL;
ps->size = ps->capacity = 0;
}
void CheckSeqListCapacity(SeqList* ps) {
if (ps->size == ps->capacity) {
SLDataType* p = (SLDataType*)realloc(ps->a, sizeof(int)*ps->capacity * 2);
if (p == NULL) {
printf("fail!");
exit(-1);
}
ps->a = p;
ps->capacity *= 2;
}
}
void SeqListPushBack(SeqList* ps,SLDataType x) {
CheckSeqListCapacity(ps);
ps->a[ps->size ] = x;
ps->size += 1;
}
void SeqListPushFront(SeqList* ps, SLDataType x) {
CheckSeqListCapacity(ps);
int end = ps->size - 1;
while (end >= 0) {
ps->a[end + 1] = ps->a[end];
end--;
}
ps->a[0] = x;
ps->size++;
}
void SeqListPopBack(SeqList* ps) {
if (ps->size == 0)return;
ps->size--;
}
void SeqListPopFront(SeqList* ps) {
if (ps->size == 0)return;
int start = 1;
while (start <= ps->size-1) {
ps->a[start - 1] = ps->a[start];
start++;
}
ps->size--;
}
void SeqListInsert(SeqList* ps, int pos,SLDataType x) {
assert(pos <= ps->size && pos > 0);
CheckSeqListCapacity(ps);
int end = ps->size - 1;
while (end >= pos) {
ps->a[end + 1] = ps->a[end];
end--;
}
ps->a[pos] = x;
ps->size++;
}
void SeqListErase(SeqList* ps, int pos) {
assert(pos < ps->size && pos>0);
int start = pos + 1;
while (start <= ps->size - 1) {
ps->a[start - 1] = ps->a[start];
start++;
}
ps->size--;
}
void SeqListPrint(SeqList* ps) {
for (int i = 0; i < ps->size; i++) {
printf("%d ", ps->a[i]);
}
printf("\n");
}
void SeqListBubbleSort(SeqList* ps) {
for (int i = ps->size - 1; i >= 1; i--) {
int flag = 1;
for (int j = 1; j <= i; j++) {
if (ps->a[j - 1] > ps->a[j]) {
int tmp = ps->a[j - 1];
ps->a[j - 1] = ps->a[j];
ps->a[j] = tmp;
flag = 0;
}
}
if (flag) break;
}
}
int SeqListBinarySearch(SeqList* ps, SLDataType x) {
SeqListBubbleSort(ps);
int left = 0, right = ps->size;
while (left < right) {
int mid = (left + right) / 2;
if (x > ps->a[mid]) {
left = mid+1;
}
else if (x < ps->a[mid]) {
right = mid;
}
if (x == ps->a[mid]) {
return mid;
}
}
return -1;
}