Create a sequential list
static final int MAXLEN=100;
class DATA{
String key;
String name;
int age;
}
class SLType
{
DATA[] ListData = new DATA[MAXLEN+1];
int ListLen;
}
Initialize sequential list
void SLInit(SLType SL) //Initialize sequential list
{
SL.ListLen = 0;
}
Insert an element in proper position
int SLInsert (SLType SL, int n, DATA data)
{
// n is the insert position
int i;
if (SL.ListLen >= MAXLEN)
{
System.out.println("SL is full,cannot insert new element");
return 0;
}
if (n<0 || n>SL.ListLen)
{
System.out.println("wrong position!")
return 0;
}
for (i=SL.ListLen;i>=n;i--)
{
SL.ListData[i+1]=SL.ListData[i];
}
SL.ListData[n]=data;
SL.ListLen++;
return 1;
}
Add new element in the last of list
int SLAdd(SLType SL, DATA data)
{
if(SL.ListLen>=MAXLEN)
{
System.out.println("SL is full");
return 0;
}else
SL.ListData[SL.ListLen++]=data;
return 1;
}
Delete element
int SLDelete(SLType SL, int n)
{
int i;
if(n<0 || n>SL.ListLen)
{
System.out.println("wrong position");
return 0;
}
for(i=n; i<SL.ListLen;i++)
{
SL.ListData[i]=SL.ListData[i++];
}
SL.ListLen--;
return 1;
}
Search element which value is x
1. Search with index:
DATA SLFindByIndex(SLType SL, int n)
{
if (n<0 || n>SL.ListLen)
{
System.out.println("wrong index");
return null;
}
return SL.ListData[n];
}
2. Search with keyword
int SLFindByKey(SLType SL, String word)
{
int i;
for(i=0;i<=SL.ListLen;i++)
{
if (SL.ListData[i].key.compareTo(word)==0)
{
return i;
}
}
return 0;
}
Display all elements
int SLDisplay(SLType SL)
{
int i;
for (i=0; i<=SL.ListLen;i++)
{
System.out.printf("(%s,%s,%d)\n",SL.ListData[i].key,
SL.ListData[i].name,SL.ListData[i].age);
}
return 0;
}