今天学习了线性表,更新一下,有兴趣的自行学习,可以结合下面的代码哦。
构建主体:
#define MAXSIZE 100
int data[MAXSIZE];
int length;
typedef struct node
{
int data[MAXSIZE];
int length;
}SeqList, *PSeqList;
PSeqList PL;
初始化:
PSeqList Init_SeqList(void) ///返回的类型就是指针。
{
PL = (PSeqList)malloc(sizeof(SeqList));
if(PL)
PL->length = 0;
return (PL);
}
主函数验证部分(同时定义了一个之后一直用的指针):
int main()
{
int t;
PSeqList L;
L = Init_SeqList(); ///把返回值拉出来,给一个名字。
t=Length_SeqList(L);
printf("%d\n",t);
Insert_SeqList(L,1,1);
t=Length_SeqList(L);
printf("%d\n",t);
t=Location_Seqlist(L, 1);
printf("%d\n",t);
Delete_SeqList(L,1);
t=Length_SeqList(L);
printf("%d\n",t);
}
显示长度:
int Length_SeqList(PSeqList L) ///注意这里的PSeqList L,是一个形参,L只是名字,重要的是类型。
{
return (L->length);
}
检索:
//检索
int Location_Seqlist(PSeqList L, int x)
{
int i = 0;
while(i<L->length && L->data[i]!=x)
i++;
if(i>= L->length) return 0;
else return (i+1);
}
插入:
//插入
int Insert_SeqList(PSeqList L,int i,int x)
{
int j;
if(!L)
{
printf("list is not exist");
return (-2);
}
if(L->length>=MAXSIZE)
{
printf("FULL");
return (-1);
}
if(i<1||i>L->length+1)
{
printf("it is illegal");
return 0 ;
}
for(j=L->length-1;j>=i-1;j--) ///i-1是插入的位置
{
L->data[j+1]=PL->data[j];
}
L->data[i-1]=x;
L->length++;
return 1;
}
删除:
//删除
int Delete_SeqList(PSeqList L,int i)
{
int j;
if(!L)
{
printf("list is not exist");
return (-1);
}
if(i<1||i<L->length)
{
printf("it is illegal");
return (0);
}
for(j=i;j<L->length;j++)
L->data[j-1] = L->data[j];
L->length--;
return 1;
}
///在写删除与添加程序的时候由于有输入的参数,要考虑到函数对各种各样的参数的反应
完整的程序如下,有需求的自取:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAXSIZE 100
int data[MAXSIZE];
int length;
typedef struct node
{
int data[MAXSIZE];
int length;
}SeqList, *PSeqList;
PSeqList PL;
PSeqList Init_SeqList(void) ///返回的类型就是指针。
{
PL = (PSeqList)malloc(sizeof(SeqList));
if(PL)
PL->length = 0;
return (PL);
}
int Length_SeqList(PSeqList L) ///注意这里的PSeqList L,是一个形参,L只是名字,重要的是类型。
{
return (L->length);
}
//检索
int Location_Seqlist(PSeqList L, int x)
{
int i = 0;
while(i<L->length && L->data[i]!=x)
i++;
if(i>= L->length) return 0;
else return (i+1);
}
//插入
int Insert_SeqList(PSeqList L,int i,int x)
{
int j;
if(!L)
{
printf("list is not exist");
return (-2);
}
if(L->length>=MAXSIZE)
{
printf("FULL");
return (-1);
}
if(i<1||i>L->length+1)
{
printf("it is illegal");
return 0 ;
}
for(j=L->length-1;j>=i-1;j--) ///i-1是插入的位置
{
L->data[j+1]=PL->data[j];
}
L->data[i-1]=x;
L->length++;
return 1;
}
//删除
int Delete_SeqList(PSeqList L,int i)
{
int j;
if(!L)
{
printf("list is not exist");
return (-1);
}
if(i<1||i<L->length)
{
printf("it is illegal");
return (0);
}
for(j=i;j<L->length;j++)
L->data[j-1] = L->data[j];
L->length--;
return 1;
}
///再写删除与添加程序的时候由于有输入的参数,要考虑到函数对各种各样的参数的反应
int main()
{
int t;
PSeqList L;
L = Init_SeqList(); ///把返回值拉出来,给一个名字。
t=Length_SeqList(L);
printf("%d\n",t);
Insert_SeqList(L,1,1);
t=Length_SeqList(L);
printf("%d\n",t);
t=Location_Seqlist(L, 1);
printf("%d\n",t);
Delete_SeqList(L,1);
t=Length_SeqList(L);
printf("%d\n",t);
}