• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Jesus Program
博客园    首页    新随笔    联系   管理    订阅  订阅
顺序表的初始化、删除、插入
Code
//初始化线性表
#include<stdio.h>
#include
<malloc.h>
#include
<stdlib.h>
#define List_init_size 100
#define Listincrement 10
#define OK 1
#define ERROR 0
#define OVERFLOW -2
struct Sqlist
{
    
char *elem;    
    
int length;
    
int listsize;
};
int InitList(Sqlist *l)
{
    l
->elem=(char *)malloc(List_init_size*sizeof(char));
    
if(!l->elem)
    {    
        printf(
"Malloc Error!\n");
         exit(OVERFLOW);
    }
    l
->length=0;
    l
->listsize=List_init_size;
    
return OK;
}
int ListInsert(Sqlist *l,int i,char e)
{
    
char *newbase;
    
char *q,*p;
    
// 在顺序线性L中第i个位置之前插入新的元素
    if(i<1||i>l->length+1)
        
return ERROR;
    
if(l->length>=l->listsize)
    {
       newbase
=(char *)realloc(l->elem,(Listincrement+List_init_size)*sizeof(char));
       
if(!newbase)
           exit(OVERFLOW);
       l
->listsize+=Listincrement;
    }
    q
=&(l->elem[i-1]);
    
for(p=&(l->elem[l->length-1]);p>=q;--p)
        
*(p+1)=*p;
    
*q=e;
    
++l->length;
    
return OK;
}
int ListDel(Sqlist *l,int i,char *e)//在顺序线性L中删除第i个元素,并用e返回其值
{
    
char *p,*q;
    
if(i<1||i>l->length)
    
return ERROR;
    p
=&(l->elem[i-1]);
    
*e=*p;
    q
=l->elem+l->length-1;
    
for(++p;p<=q;++p)
        
*(p-1)=*p;
    
--l->length;
    
return OK;
}
void print(Sqlist *l)
{
    
int i;
    
for(i=0;i<l->length;i++)
        printf(
"%c\n",l->elem[i]);
}
int main()
{
    Sqlist l;
    
char elem;
    InitList(
&l);
        ListInsert(
&l,1,'a');
    ListInsert(
&l,2,'b');
    print(
&l);    
        ListDel(
&l,1,&elem); 
        printf(
"Del:%c\n",elem);
    print(
&l);
        
return OK;
}
posted on 2009-09-19 19:24  Jesus Program  阅读(409)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3