`
bsr1983
  • 浏览: 1100790 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

C语言实现的顺序链表代码

阅读更多

      数据结构上机考试练习代码,置于此以备后用!

 

    

#include<stdio.h>
#define ListSize 100
//定义顺序表存放的数据类型
typedef int DataType;
//定义顺序表的结构
typedef struct{
    //用于存放元素的数组
    DataType data[ListSize];
    //用于标示顺序表元素个数的变量
    int length;
}Seqlist;
//顺序表插入
void InsertList(Seqlist *L,DataType x,int i)
{
    int j;
    //如果插入位置i小于1或大于当前顺序表长度,则提示出错
    if(i<1||i>L->length+1)
    {
        Error("position error");
        return;
    }
    //如果当前顺序表长度已达峰值,则提示溢出
    if(L->length>=ListSize)
    {
        Error("overflow");
        return;
    }
    //循环后移插入位置及其后边的元素
    for(j=L->length-1;j>i-1;j--)
    {
        L->data[j+1]=L->data[j];
    }
    //插入数据
    L->data[i-1]=x;
    L->length++;
}
//打印错误
void Error(char *c)
{
     printf("there is a error : %s \n",c);
}
void DeleteList(Seqlist *L,int i)
{
    int j;
    //如果当前顺序表的长度为0,则提示当前顺序表为空
    if(L->length==0)
    {
        Error("this list is null");
    }
    //如果当前指定的位置小于1或大于表长,则提示其位置错误
    else if(i<1||i>L->length)
    {
        Error("position error");
    }
    else
    {
         //否则,循环将位置i之后的原始顺序前移一位
        for(j=i;j<=L->length-1;j++)
        {
            L->data[j-1]=L->data[j];
        }
        //表长减1
         L->length--;
    }

}
//打印表中所有元素
void PrintList(Seqlist *L)
{
    int i;
     //如果当前顺序表的长度为0,则提示当前顺序表为空
    if(L->length==0)
    {
        Error("this list is null");
        return;
    }
    else
    {
        for(i=0;i<L->length-1;i++)
        {
           printf("%d ",L->data[i]);
        }
    }
}
int main()
{
    int i;
    Seqlist *list;
    list=(Seqlist*)malloc(sizeof(list));
    for(i=1;i<ListSize;i++)
    {
       InsertList(list,i,i);
    }
    PrintList(list);
    printf("the data element of seqlist is %d \n",list->length);
    DeleteList(list,20);
    printf("the data element of seqlist is %d \n",list->length);
    free(list);//释放list所占用内存
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics