一、顺序表
头文件:
typedef struct{
int *p;// 将来存放动态分配的数组首地址
int nowLength;// 当前储存了几个数
int maxSize;// 最大存储空间
}Order;
简单使用:
Order orderStructA;
orderInit(orderStructA);
orderInsert(orderStructA,5,1);
orderDelete(orderStructA,1);
1 初始化
void orderInit(Order &orderStruct)
{
int *arr;
// 动态分配
orderStruct.maxSize=10;
orderStruct.nowLength=0;
arr = (int*)malloc(sizeof(int)*(orderStruct.maxSize));
// 动态分配失败退出
if(!arr)
{
printf("程序异常退出");
exit(-3);
}
orderStruct.p=arr;
}
2 插入
int orderInsert(Order &orderStruct,int data,int position)
{
//检查
if(position>orderStruct.maxSize)
{
int *arr;
orderStruct.maxSize+=10;
// 再分配
arr = (int*)realloc(orderStruct.p,sizeof(int)*(orderStruct.maxSize));
if(!arr)
{
printf("程序异常退出");
exit(-3);
}else
{
orderStruct.p=arr;
}
}
else if(position<1)
{
printf("不合法输入\n");
return 0;
}+
position--;
int i;
// 从后往前给值
for(i=orderStruct.nowLength; i>position; i--)
{
*(orderStruct.p+i)=*(orderStruct.p+i-1);
}
// 此时i减到应该赋值的位置,进行赋值即可
*(orderStruct.p+i)=data;
orderStruct.nowLength++;
return 1;
}
3 删除
int orderDelete(Order &orderStruct,int position)
{
int i;
//检查
if(position<1||position>orderStruct.nowLength)
{
printf("不合法输入\n");
return 0;
}
position--;
int tem = *(orderStruct.p+position);
for(i=position; i<orderStruct.nowLength-1; i++)
{
*(orderStruct.p+i)=*(orderStruct.p+i+1);
}
orderStruct.nowLength--;
return tem;
}
二、单链表
头文件:
typedef struct link{
int data;
struct link *next;
}Link;
简单使用:
Order orderStructA;
orderInit(orderStructA);
orderInsert(orderStructA,5,1);
orderDelete(orderStructA,1);
1 初始化
Link* linkInit()
{
Link *head=(Link*)malloc(sizeof(Link));
head->data=0;
head->next=NULL;
return head;
}
2 插入
int linkInsert(Link *head,int data,int position)
{
int i;
Link *p=head;// 关键处理与linkIndex不同在这里
position--;
// i<position是为了定位到添加元素位置的前一位,&&p是处理当用户恶意输入position大于链表长度时指向空指针,空指针求next就会出错
for(i=0;i<position&&p;i++){
p=p->next;
}
// 两种情况①position超出范围最后指向空②position为负数
if(!p||position<0){
return -1;
}
// 正常
Link *node = (Link*)malloc(sizeof(Link));
node->data=data;
node->next=p->next;
p->next=node;
return 1;
}
3 删除
int linkDelete(Link *head,int position)
{
// 1 2 3 4 {} 例子(position--后为1)
int i;
position--;
Link *p=head;// 关键处理与linkIndex不同在这里
// 遍历时,避免position为负数,以及position超出范围的情况(需要定位到删除元素前一位)
for(i=0; i<position&&p; i++)
{
p=p->next;
}
// 两种情况①position超出范围最后指向空②position为负数
if(!p||position<0)
{
return -1;
}
// 正常情况
Link *destory = p->next;
int destoryData = p->next->data;
p->next=p->next->next;
free(destory);
return destoryData;
}
4 下标反值
int linkIndex(Link *head,int position)
{
// 1 2 3 4 {} 例子(position--后为3)
int i;
position--;
Link *p=head->next;
// 遍历时,避免position为负数,以及position超出范围的情况(需要定位到查找元素)
for(i=0; i<position&&p; i++)
{
p=p->next;
}
// 两种情况①position超出范围最后指向空②position为负数
if(!p||position<0)
{
return -1;
}
// 正常情况
return p->data;
}