順序表的簡單實現(Java)

來源:互聯網
上載者:User

採用Java實現資料結構中的順序表

/** *Apr 15, 2013 *Copyright(c)JackWang *All rights reserve *@Author <a href="mailto:wangchengjack@163.com">JackWang</a>*/package com.example.list;/** * 順序表的實現 * @author Administrator * */public class MySeqList {private Object[] obj; //儲存元素,初始長度為10private int len;   //記錄順序表的長度private final int maxSize = 10;/** * 初始化線性表 */public MySeqList() {this.obj = new Object[10];this.len = 0;this.clear();}/** * 判斷線性表是否為空白 * @return 空返回true */public boolean isEmpty(){if (len == 0) {return true;}return false;} /** * 判斷線性表是否已滿 * @return 滿返回 true */public boolean isFull(){if (len == maxSize) {return true;}return false;}/** * 返回線性表的長度 * @return 線性表的長度 */public int length(){return len;}/** * 清空線性表 */public void clear() {for (int i = 0; i < obj.length; i++) {obj[i] = null;}}/** * 添加元素 * @param i  要添加元素的腳標 * @param o  要添加的元素 */public void insert(int i,Object o){if (i <1) {throw new RuntimeException("腳標不規範!");}if (obj[i-1] != null) {for(int j = len-1;j>i;j--){obj[j+1] = obj[j];}obj[i] = o;len++;return;}else {obj[i-1] = o;len++;return;}}/** * 刪除元素 * @param i 要刪除的元素索引 */public void delete(int i){if (i > len || i <1) {throw new RuntimeException("腳標不規範!");}for(int j = i;j<len-1;j++){obj[i-1]=obj[i];}obj[len-1] = null;len--;}/** * 修改元素 * @param i  要修改元素的腳標 * @param newObj 要修改的值 */public void update(int i,Object newObj){if (i > len || i <1) {throw new RuntimeException("腳標不規範!");}obj[i-1] = newObj;}/** * 尋找元素 * @param o  要尋找的元素 * @return   查到元素的索引 */public int find(Object o){for (int i = 0; i < obj.length; i++) {if(o.equals(obj[i])){return i+1;}}return -1;}/** * 當前元素的前一個元素的索引 */public int previous(int i){if (i > len || i <1) {throw new RuntimeException("腳標不規範!");}if( i== 1){return len;}return i-1;}/** * 當前元素的後一個元素的索引 */public int next(int i){if (i > len || i <1) {throw new RuntimeException("腳標不規範!");}if( i == len){return 1;}return i+1;}/** * 遍曆輸出線性表 * @return  */public void print(){for (int i = 0; i < obj.length; i++) {System.out.println(obj[i]+" ");}System.out.println();}/** * 得到特定腳標的元素 * @param i * @return */public Object get(int i){if (i > len || i <1) {throw new RuntimeException("腳標不規範!");}return obj[i-1];}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.