数据结构之——顺序表
顺序表是指用一组地址连续的存储单元依次存储数据元素的线性结构。线性表采用顺序存储的方式存储就称之为顺序表,顺序表是将表中的结点依次存放在计算机内存中一组地址连续的存储单元中。线性表采用指针链接的方式存储就称之为链表。
数组是从物理存贮的角度来说的,线性表可以用数组存贮也可以用链表来存贮。同样的队列和栈也可以用数组和链表存贮,各有利弊。具体使用时,根据具体情况选择。
所以说,数组是一个更大的概念。使用数组,不但可以存储线性表,也可存储非线性结构的数据结构。如堆、完全二叉树、乃至于其它类型的树、图等。
package lijian;
import java.util.Scanner;
class DATA{
String key;
String name;
int age;
}
class SLType{
staticfinalintMAXLEN=100;
DATA[] ListData= new DATA[MAXLEN+1];
int ListLen;
void SLInit(SLType SL){
SL.ListLen=0;//初始化顺序表
}
int SLLength(SLType SL){
return SL.ListLen;
}
int SLInsert(SLType SL,int n,DATA data){
int i;
if (SL.ListLen>=MAXLEN) {
System.out.println(“顺序表已满,不能插入节点”);
return 0;
}
if(n<1 || n>SL.ListLen){
System.out.println(“插入元素需要错误”);
return 0;
}
for(i=SL.ListLen;i>=n;i–){
SL.ListData[i+1]=SL.ListData[i];
}
SL.ListData[n]=data;
SL.ListLen++;
return 1;
}
int SLAdd(SLType SL,DATA data){
if(SL.ListLen>=MAXLEN){
System.out.println(“顺序表已满,不能在添加节点”);
return 0;
}
SL.ListData[++SL.ListLen]=data;
return 1;
}
int SLDelete(SLType SL,int n){
int i;
if(n<1 || n>SL.ListLen+1){
System.out.println(“节点错误,不能删除”);
return 0;
}
for(i=n;i<SL.ListLen;i++){
SL.ListData[i]=SL.ListData[i+1];
}
SL.ListLen–;
return 1;
}
DATA SLFindByNum(SLType SL,int n){
if (n<1 || n>SL.ListLen) {
System.out.println(“结点序号错误”);
returnnull;
}
return SL.ListData[n];
}
int SLAll(SLType SL){
int i;
for(i=1;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;
}
}
public class ll {
public static void main(String[] args) {
int i;
SLType SL=new SLType();
DATA pdata;
System.out.println(“顺序表演示操作”);
Scanner input=new Scanner(System.in);
do{
System.out.print(“输入添加学生的学号,姓名,年龄\n”);
DATA data=new DATA();
data.key=input.next();
data.name=input.next();
data.age=input.nextInt();
if (data.age!=0) {
if(SL.SLAdd(SL, data)==0){
System.out.println(“插入节点失败\n”);
break;
}
else {
System.out.println(“插入成功”);
break;
}
}else {
System.out.println(“年龄不能为零\n”);
break;
}
}while (true);
SL.SLAll(SL);
System.out.println(“输出要取出的节点序号”);
i=input.nextInt();
pdata=SL.SLFindByNum(SL, i);
if(pdata!=null){
System.out.printf(“%s %s %d\n”,pdata.key,pdata.name,pdata.age);
}
}
}