线性表的基本操作:新建,插入,删除,查找(C语言版)

来源:互联网 发布:广州多益网络招聘 编辑:程序博客网 时间:2024/05/18 05:39
//可提前阅读《结构体指针的定义和使用》:http://blog.csdn.net/xiaohuizi2009/article/details/8629401//1、线性表的初始化,插入,删除相同某个元素,删除某个位置的元素,查找元素,输出元素//只能顺序插入,若间隔插入有问题??#include<stdlib.h>#include<stdio.h>#include<malloc.h>struct LinerList//定义线性表结构{//强化理解这里*list号的含义,保证L->list[i]不报错:表达式必须包含指向对象的指针类型//以及(L->list=(int*)malloc(ms*sizeof(int)))==NULL)正常分配         int *list;//存线性表元素                  int size;//存线性表长度int MAXSIZE;//存list数组元素个数};typedef struct LinerList LIST;void InitLIST(LIST *L,int ms){//初始化线性表if((L->list=(int*)malloc(ms*sizeof(int)))==NULL){printf("内存申请失败!\n");exit(1);}L->size=0;L->MAXSIZE=ms;}int InsertLIST(LIST *L,int item,int rc){//将item插入线性表L的rc位置//item为记录值,rc为插入位置 int i;if(L->size==L->MAXSIZE) //线性表已满return -1;if(rc<0)//插入位置为0到L->sizerc=0;if(rc>L->size)for(i=L->size-1;i>=rc;i--)//L[i+1]=L[i];L->list[i+1]=L->list[i];//线性表元素后移L->list[rc]=item;L->size++;return 0;}void OutputLIST(LIST *L){//输出线性表元素int i;for(i=0;i<L->size;i++)printf("%d ",L->list[i]);printf("\n");}int FindLIST(LIST *L,int item){//寻找线性表元素,返回≥0为元素位置,-1为没找到int i;for(i=0;i<L->size;i++){if(item==L->list[i])//找到相同元素,返回位置return i;}return -1;}int DeleteLIST1(LIST *L,int item)//找到相同元素进行删除{//删除指定元素值的线性表记录,返回≥0为删除成功int i,n;for(i=0;i<L->size;i++)if(item==L->list[i])break;if(i<L->size){for(n=i;n<L->size-1;n++)L->list[n]=L->list[n+1];L->size--;return i;}return -1;}int DeleteLIST2(LIST *L,int rc){//删除指定rc位置的元素记录int i;if(rc<0||rc>=L->size)return -1;for(int i=rc;i<L->size-1;i++)L->list[i]=L->list[i+1];L->size--;return 0;}void main(){LIST LL;int i,r;//printf("LIST addr=%p\tsize=%d\tMaxSize=%d\n",LL.list,LL.size,LL.MAXSIZE);InitLIST(&LL,10);printf("LIST addr=%p\tsize=%d\tMaxSize=%d\n",LL.list,LL.size,LL.MAXSIZE);OutputLIST(&LL);while(1){printf("请输入元素值,输入0结束插入操作:");fflush(stdin);scanf("%d",&i);if(i==0)break;printf("请输入插入位置:");scanf("%d",&r);InsertLIST(&LL,i,r-1);printf("线性表为: ");OutputLIST(&LL);}while(1){printf("请输入查找的元素值,输入0结束插入操作:");fflush(stdin);scanf("%d",&i);if(i==0)break;r=FindLIST(&LL,i);if(r<0)printf("没找到!");elseprintf("有符合条件的元素,位置为:%d\n",r+1);}while(1){printf("请输入删除元素值,输入0结束查找操作:");fflush(stdin);scanf("%d",&i);if(i==0)break;r=DeleteLIST1(&LL,i);if(r<0)printf("没找到!");else{printf("有符合条件的元素,位置为:%d\n",r+1);OutputLIST(&LL);}}while(1){printf("请输入删除元素位置,输入0结束删除操作:");fflush(stdin);scanf("%d",&r);if(r==0)break;i=DeleteLIST2(&LL,r-1);if(i<0)printf("位置越界\n");else{printf("线性表为:");OutputLIST(&LL);}}}

原创粉丝点击