顺序表
来源:互联网 发布:淘宝网经营模式 编辑:程序博客网 时间:2024/04/30 13:49
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- class LineList
- {
- private Object[] data;
- private int length;
-
- public LineList(){}
- public LineList(Object[] data)
- {
- this.data = data;
- length = data.length;
- }
- public void setData(Object[] data) {this.data = data;}
-
- public Object[] getData()
- {
- Object[] response = new Object[length];
- for(int i = 0; i < length; i++)
- response[i] = data[i];
- return response;
- }
-
- public void setLength(int length) {this.length = length;}
- public int getLength() {return length;}
-
- public boolean insert(int index, Object obj)
- {
- if(length >= data.length)
- {
- System.out.println("The table is overflow.");
- return false;
- }
- if(index < 1 || index > length)
- {
- System.out.println("The position is mistake: " + index);
- return false;
- }
-
- --index;
- for(int i = length-1; i >= index; i--)
- data[i+1] = data[i];
-
- data[index] = obj;
- length++;
- return true;
- }
-
- public boolean delete(int index)
- {
- if(length < 1)
- {
- System.out.println("The table is null");
- return false;
- }
- if(index < 1 || index > length)
- {
- System.out.println("The position is mistake: " + index);
- return false;
- }
-
- int len = length-1;
- for(int i = index-1; i < len; i++)
- data[i] = data[i+1];
- length--;
- return true;
- }
-
- public int find(Object obj)
- {
- for(int i = 0; i <= length; i++)
- if(data[i] == obj)
- return i+1;
-
- return -1;
- }
-
- public boolean replace(int index, Object obj)
- {
- if(index < 1 || index > length)
- {
- System.out.println("The position is mistak: " + index);
- return false;
- }
-
- data[index-1] = obj;
- return true;
- }
- }
-
- class Test
- {
- public static void main(String[] args)
- {
- Integer[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- LineList lineList = new LineList(a);
- lineList.insert(0, 5);
- lineList.delete(2);
- lineList.insert(5, 13);
-
-
-
-
-
-
-
-
-
- lineList.replace(10, 18);
- System.out.println("lineList's length: " + lineList.getLength());
- Object[] response = lineList.getData();
-
- System.out.println("find " + 5 + ": " + lineList.find(5));
- for(int i = 0; i < response.length; i++)
- System.out.print(response[i] + " ");
- }
- }