zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    AcWing 157. 树形地铁系统 (hash判断树同构)打卡
    AcWing 156. 矩阵 (哈希二维转一维查询)打卡
    AcWing 144. 最长异或值路径 01字典树打卡
    AcWing 143. 最大异或对 01字典树打卡
    AcWing 142. 前缀统计 字典树打卡
    AcWing 139. 回文子串的最大长度 hash打卡
    AcWing 138. 兔子与兔子 hash打卡
    常用C库函数功能及用法
    编程实现C库函数
    C语言面试题5
  • 原文地址:https://www.cnblogs.com/xurui1995/p/5178341.html
Copyright © 2011-2022 走看看