Java-實現順序表的基本操做

List.java

package com.wanali.java_ds.sqlist;
public interface List {
	public boolean empty();
	public void clear();
	public int length();
	public Object get(int i);
	public void insert(int i, Object x) throws Exception;
	public Object delete(int i);
	public void display();
SqList.java

package com.wanali.java_ds.sqlist;

public class SqList implements List {
	private Object[] elem;
	private int curlength;

	public SqList(int maxsize) {
		curlength = 1;
		elem = new Object[maxsize];
	}

	public boolean empty() {
		return curlength == 0;
	}

	public int length() {
		// TODO Auto-generated method stub
		return curlength;
	}

	public void clear() {
		curlength = 0;
		System.out.println("表已經清空了!!!");
	}

	public Object get1(int i) {
		return elem[i - 1];

	}

	public void insert(int i, Object x) throws Exception {
		if (i < 0 || i > curlength)
			throw new Exception("輸入的參數不合法");
		int maxsize = 10;
		if (curlength == elem.length)
			elem[maxsize] = elem[2 * maxsize];
		for (int j = curlength; j > i; j--)
			elem[j] = elem[j - 1];
		elem[i] = x;
		++curlength;
	}

	public Object delete(int i) {
		for (int j = i; j < curlength; j++)
			elem[j] = elem[j + 1];
		--curlength;
		return elem[i];
	}

	public void display() {
		// TODO Auto-generated method stub
		for (int i = 1; i < curlength; i++)
			System.out.println(elem[i]);
	}

	public Object get(int i) {
		// TODO Auto-generated method stub
		System.out.println(elem[i]);
		return null;
	}

}
TestSqList.java

package com.wanali.java_ds.sqlist;

public class TestSqList {
	public static void main(String[] args) {
		SqList sqList = new SqList(10);
		try {
			sqList.insert(1, 10);
			sqList.insert(2, 20);
			sqList.insert(3, 30);
			sqList.insert(4, 40);
                        System.out.println("按順序輸出表中的元素:");
			sqList.display();
			System.out.println("刪除一個元素:");
			sqList.delete(2);
			sqList.display();
			System.out.println("得到第i個元素:");
			sqList.get(2);
			System.out.println("清空順序表:");
			sqList.clear();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

運行結果以下:java

運行結果

相關文章
相關標籤/搜索