数据结构——动态顺序表(DEV C++版本)

之前写的动态顺序表是在vs2022中完成的,为了照顾没有vs2022的家人,发布一篇DEV版本

c 复制代码
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef struct {
	int *arr;
	int size;
	int capacity;
}SL;
SL s;
void init(SL* ps)
{
	ps->arr=NULL;
	ps->capacity=0;
	ps->size=0;
 } 
 void print(SL* ps)
 {
 	int i=0;
 	for(i=0;i<ps->size;i++)
 	{
 		printf("%d  ",ps->arr[i]);
	 }
	 printf("\n");
 }
 void check(SL* ps)
 {
 	int newcapacity=ps->capacity==0?4:2*ps->capacity;
 	if(ps->size==ps->capacity)
 	{
 		int* temp=(int*)realloc(ps->arr,sizeof(int)*2*ps->capacity);
 		if(temp==NULL)
 		{
 			printf("error\n");
 			exit(-1);
		 }
		 else
		 {
		 	ps->arr=temp;
		 	ps->capacity=newcapacity;
		 }
	 }
 }
 void pushback(SL* ps,int x)
 {
 	
 	check(ps);
 	ps->arr[ps->size]=x;
 	ps->size++;
 }
 void pushfront(SL* ps,int x)
 {
 	check(ps);
 	int end=ps->size-1;
 	while(end>=0)
 	{
 		ps->arr[end+1]=ps->arr[end];
 		end--;
	 }
	 ps->size++;
	 ps->arr[0]=x;
 }
 void deleteback(SL* ps)
 {
 	ps->size--;
 }
 void deletefront(SL* ps)
 {
 	int tail=1;
 	while(tail<ps->size)
 	{
 		ps->arr[tail-1]=ps->arr[tail];
 		tail++;
	 }
	 ps->size--;
 }
 void pushrandom(SL* ps,int index,int x)
 {
 	assert(index<=ps->size);
 	check(ps);
 	int end=ps->size;
 	while(end>index)
 	{
 		ps->arr[end]=ps->arr[end-1];
 		end--;
	 }
	 ps->arr[index]=x;
	 ps->size++;
 }
 void deleterandom(SL* ps,int index)
 {
 	assert(index<ps->size);
 	int begin =index;
 	while(begin<=ps->size-1)
 	{
 		ps->arr[begin]=ps->arr[begin+1];
 		begin++;
	 }
	 ps->size--;
 }
 void updata(SL* ps,int index,int x)
 {
 	ps->arr[index]=x;
 }
 void test()
 {
 	init(&s);
 	pushback(&s,2);
 	pushback(&s,1);
 	pushback(&s,1);
 	pushfront(&s,5);
 	pushfront(&s,8);
 	pushfront(&s,9);
 	print(&s); 
 	deleteback(&s);
 	deleteback(&s);
 	deletefront(&s);
 	deletefront(&s);
 	print(&s);
 	pushrandom(&s,1,5);
 	print(&s);
 	pushrandom(&s,1,9);
 	print(&s);
 	pushrandom(&s,1,8);
 	print(&s);
 	pushrandom(&s,1,2);
 	print(&s);
 	pushrandom(&s,1,3);
 	print(&s);
 	deleterandom(&s,1);
 	print(&s);
 	deleterandom(&s,1);
 	print(&s);
 	deleterandom(&s,1);
 	print(&s);
 	deleterandom(&s,1);
 	print(&s);
 	deleterandom(&s,1);
 	print(&s);
 	updata(&s,0,2);
 	print(&s);
 }
 int main()
 {
 	test();
 	free(s.arr);
 	return 0;
 }
相关推荐
艾莉丝努力练剑3 分钟前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途2 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
珊瑚里的鱼5 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
不知道叫什么呀5 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc
秋说6 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
lifallen6 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka
liupenglove7 小时前
自动驾驶数据仓库:时间片合并算法。
大数据·数据仓库·算法·elasticsearch·自动驾驶
python_tty8 小时前
排序算法(二):插入排序
算法·排序算法
然我8 小时前
面试官:如何判断元素是否出现过?我:三种哈希方法任你选
前端·javascript·算法
risc1234568 小时前
BKD 树(Block KD-Tree)Lucene
java·数据结构·lucene