• java语言建立顺序表


     1 package datastructure;
     2 //线性表
     3 
     4 public interface IList {
     5     public void clear();
     6     public boolean isEmpty();
     7     public int length();
     8     public Object get(int i) throws Exception;
     9     public void insert(int i,Object x) throws Exception;
    10     public void remove(int i) throws Exception;
    11     public int indexOf(Object x);
    12     public void display();
    13 
    14 }
     1 package datastructure;
     2 //顺序表
     3 
     4 public class SqList implements IList {
     5     private Object[] listElem;
     6     private int curLen;
     7     public SqList(int maxSize){
     8         curLen =0;
     9         listElem = new Object[maxSize];
    10     }
    11     public void clear() {
    12         curLen=0;
    13     }
    14     public boolean isEmpty() {
    15         
    16         return curLen==0;
    17     }
    18     public int length() {
    19         
    20         return curLen;
    21     }
    22     public Object get(int i) throws Exception {
    23         if(i<0||i>curLen-1)
    24             throw new Exception("第"+i+"个元素不存在");
    25         
    26         return listElem[i];
    27     }
    28     
    29     public void insert(int i, Object x) throws Exception {
    30         if(curLen==listElem.length)
    31             throw new Exception("顺序表已满");
    32         if(i<0||i>curLen)
    33             throw new Exception("插入位置不合法");
    34         for(int j=curLen;j>i;j--)
    35             listElem[j]=listElem[j-1];
    36            listElem[i]=x;
    37            curLen++;
    38     }
    39     public void remove(int i) throws Exception {
    40         if(i<0||i>curLen-1)
    41             throw new Exception("删除位置不合法");
    42         for(int j=i;j<curLen-1;j++)
    43             listElem[j]=listElem[j+1];
    44                 curLen--;
    45         
    46     }
    47     public int indexOf(Object x) {
    48         int j=0;
    49         while(j<curLen&&!listElem[j].equals(x))
    50             j++;
    51         if(j<curLen)
    52             return j;
    53         else
    54         return -1;
    55     }
    56     public void display() {
    57         for(int j=0;j<curLen;j++)
    58             System.out.print(listElem[j]+" ");
    59         System.out.println();
    60     }
    61     
    62 }
  • 相关阅读:
    java基础学习
    形参和返回值
    内部类
    常用API(String、StringBuilder)【1】
    什么是servlet
    servlet2.5和3.0的区别,servlet4.0注解
    什么是事务
    jdk环境配置(转载)
    idea中运行Tomcat后控制台出现乱码(统一设置成UTF-8)
    java数组
  • 原文地址:https://www.cnblogs.com/xurui1995/p/5178341.html
Copyright © 2020-2023  润新知