`
qinweiping
  • 浏览: 128330 次
  • 性别: Icon_minigender_1
  • 来自: 嘉兴
社区版块
存档分类
最新评论

C语言数据结构实战(一)顺序表的插入与删除

阅读更多

今天学习了思成老师的数据结构实战教程 写了一个顺序表 插入和删除的操作 把源码共享给大家 一共包括list.c stu.h main.c list.h   .h文件是头文件 需要引入 具体的功能我都已经在代码中写明了 

list.h代码如下:

//线性表的定义在头文件中实现
#ifndef _LIST_H
#define _LIST_H

#define _LIST_INIT_SIZE 10
#define _LIST_INCREME   10

typedef struct
{
  ElemType * elem;//首地址
  int        length;
  int         size;
}LIST;

LIST *InitList();
void FreeList(LIST *l);
int InsertList(LIST *l,int i,ElemType *e);
int DeleteList(LIST *l,int i);
#endif

 list.c代码如下

#include <stdlib.h>
#include <stdio.h>
#include "stu.h"
#include "list.h"
//线性表的初始化,此时数据存储的大小的内存还未开辟 开辟的是list.h的大小
LIST *InitList()
{
  LIST *l=(LIST *)malloc(sizeof(LIST));
  //判断开辟是否成功
  if(l==NULL)
    exit(0);
  //开辟存储数据的内存的区域
    l->elem=(ElemType *)malloc(_LIST_INIT_SIZE *sizeof(ElemType));
    //如果开辟成功的话就释放掉内存
    if(l->elem==NULL)
    {
	  free(l);
	  exit(0);
	}
	//有效长度赋初值为0
	l->length=0;
	l->size=_LIST_INIT_SIZE;
	return l;
}
//释放对区内存的函数
void FreeList(LIST *l)
{
  //要先释放成员的空间
  free(l->elem);
  free(l);
}
//第一个参数要传得是插入哪一个线性表中去 i指位置 
int InsertList(LIST *l,int i,ElemType *e)
{
  //定义一些指针 指向相应的位置
  ElemType *p=NULL,*q=NULL,*newElem=NULL;
  if(l==NULL || e==NULL)
  return 0;
  	//i指的是第几个位置 不是下标
  if(i<1||i>l->length+1)
  return 0;
  //if有效长度大于最大的长度的时候 重新开辟一块内存
  if(l->length>=l->size)
  {
  	
    newElem=realloc(l->elem,(l->size+_LIST_INCREME)*sizeof(ElemType));
    if(newElem==NULL)
    return 0;
    l->elem=newElem;
    l->size+=_LIST_INCREME;
    
  }
  	//q指向插入的位置 i-1代表下标
  q=&l->elem[i-1];
  	//指向最后一个有效的数据元素
  for(p=&(l->elem[l->length-1]);p>=q;p--)
     *(p+1)=*p;
     *q=*e;
     ++l->length;
     return 1;
}

int DeleteList(LIST *l,int i)
{ 
  ElemType *p=NULL,*q=NULL;
  if(l=NULL)
  return 0;
  if(i<1|| i>l->length)
  return 0;
  p=&l->elem[i-1];
  q=&l->elem[l->length-1];
  for(;p<q;p++)
    *p=*(p+1);
    --l->length;
    return 1;
}

 stu.h代码如下

#ifndef _STU_H
#define _STU_H
//定义一个学生的结构体
typedef struct
{
  char sno[4];
  char name[21];
  char  sex[3];
  int score;
}ElemType;

#endif

 main.c代码如下

#include <stdio.h>
#include "stu.h"
#include "list.h"

ElemType stu[3]={
   {"S101","张三","男",80},
   {"S102","小红","女",75},
   {"S103","王五","男",90},

};
void main()
{
  int i; 
  
  LIST *list=NULL;
  //通过函数初始化空间
  list=InitList();
  for(i=0;i<3;i++)
    InsertList(list,1,&stu[i]);
    DeleteList(list,2);
  FreeList(list);
}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics