文章给出用C语言实现顺序存储(向量)方式的线性表常用操作源代码,包括建立、输出、删除节点、插入节点。在Vc++6.0环境中调试通过。
环境:Vc++6.0
源代码如下:
源码下载:顺序存储方式的线性表操作源码(全).cpp
顺序存储方式的线性表操作源码(指针方式).cpp
// arrayCreate.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdio.h"
#include "malloc.h"
#define N 20 //define v array max length
struct list //define struct type name is list
{
int len;
int v[N];
};
typedef struct list LIST; //redefine list ist LIST or rename with caplock
void main()
{
LIST mylist; //define variable
int pos;
int x;
//mylist=(LIST*)malloc(sizeof(LIST));
void myinput(LIST *alist); //declare myinput function
void myoutput(LIST *alist); //declare myoutput function
void myDelete(LIST *alist,int position);
void myInsert(LIST *alist,int position,int x);
printf("the example of the array list as follows ");
myinput(&mylist); //call myinput
myoutput(&mylist); //call myoutput
//delete a value
printf("input the position off the array list deleted ");
scanf("%d",&pos);
myDelete(&mylist,pos);
myoutput(&mylist);
//insert a value
printf("please input the position and data to insert ");
scanf("%d,%d",&pos,&x);
myInsert(&mylist,pos,x);
myoutput(&mylist);
}
void myinput(LIST *alist)
{
int i,len,t;
printf("input the length of the array list ");
scanf("%d",&len);
if (len>N )
{
printf("the value is out of he length of the array list ");
return ;
};
//(*alist).len=len; //this statement same as follows
alist->len=len;
printf("input the data of the array list ");
for (i=0;i<alist->len;i++)
{
scanf ("%d",&t);
alist->v[i]=t;
}
}
void myoutput(LIST *alist)
{
int i;
printf("the data of the array list is ");
for (i=0;i<alist->len;i++)
{
printf("%d ",alist->v[i]);
}
printf(" ");
}
void myDelete(LIST *alist,int position)
{
int j;
if ((position>alist->len)||(alist->len<=0))
{
printf(" there is no data to delete ");
return;
}
printf("the data of the array list [%d] to delete ",position);
printf("%d ",alist->v[position]);
for (j=position;j<alist->len;j++)
{
alist->v[j]=alist->v[j+1];
}
alist->len=alist->len-1;
printf(" ");
}
void myInsert(LIST *alist,int position,int x)
{
int j;
if ((position>alist->len)||(alist->len<0))
{
printf(" there is no place to insert ");
return;
}
for (j=alist->len-1;j>=position;j--)
{
alist->v[j+1]=alist->v[j];
}
alist->v[position]=x;
alist->len=alist->len+1;
printf(" ");
}