首页 > 其他分享 >顺序表-00007-扩容

顺序表-00007-扩容

时间:2022-12-04 02:33:51浏览次数:37  
标签:扩容 顺序 capacity int pNew 00007 seqType plist inc

  • 顺序表结构定义
  • typedef int seqType;	// 定义顺序表数据类型
    
    // 定义顺序表的结构体
    typedef struct t_sList
    {
    	seqType* pbase;		// 表基址
    	int capacity;		// 表容量
    	int size;			// 表长度
    }mySList;
    

      

  • 顺序表扩容函数
  • /**
    * @brief 功能:扩容 \n
    * @param[in] plist:表结构指针
    * @param[in] inc:在表当前容量capacity上扩容inc,令total=capacity+inc,
    * @param[in] inc:若total<capacity*DOUBLE,则令total=capacity*DOUBLE
    * @retval OK(1):扩容成功
    * @retval ERROR(0):表结构不存在,不可操作
    * @retval OVERFLOW(-2):扩容失败:申请堆空间失败导致
    */
    status sList_expand(mySList* plist, int inc)
    {
    	if (plist == NULL || plist->pbase == NULL)
    	{
    		return ERROR;
    	}
    	int c = plist->capacity * DOUBLE;
    	int total = (plist->capacity + inc < c) ? c : (plist->capacity + inc);
    	seqType* pNew = NULL;
    
    #if 1	// 用realloc,更方便
    	pNew = (seqType*)realloc(plist->pbase, sizeof(seqType) * total);
    	if (pNew == NULL)
    	{
    		return OVERFLOW;
    	}
    #endif 
    
    #if 0	// 用malloc与memmove,自己实现
    	pNew = (seqType*)malloc(sizeof(seqType) * total);
    	if (pNew == NULL)
    	{
    		return OVERFLOW;
    	}
    
    	/*
    		for (int i = 0; i < plist->capacity; i++)
    		{
    			pNew[i] = plist->pbase[i];
    		}// 用malloc会发出缓冲区可能溢出的警告
    	*/
    	memmove(pNew, plist->pbase, sizeof(seqType) * (plist->capacity));
    	free(plist->pbase);
    #endif // 0
    
    	plist->pbase = pNew;
    	plist->capacity = total;
    	return OK;
    }//性能时高时低,性能低时是因为表满,需要扩容,将数据拷贝,导致的性能降低
    

      

标签:扩容,顺序,capacity,int,pNew,00007,seqType,plist,inc
From: https://www.cnblogs.com/kxwslmsps/p/16949307.html

相关文章