Java基础之线性表

package LinearTable;

import java.io.InputStream;
import java.util.Scanner;

import org.omg.CORBA.Current;


class LinList{
    private int  CurrentLength;
    private Object[] Node;
    
    public LinList(int maxlen) {
        Node=new Object[maxlen];
        CurrentLength=0;
        
    }
    public Object GetAnElement(int i) {
        return Node[i];
    }
    public void add(Object node) {  //添加元素的基本方法
        Node[CurrentLength]=node;
        CurrentLength++;
        
    }
    public void insert(int a,Object node) throws Exception{ //插入元素
        
        if(a<0||a>CurrentLength){
            
            throw new Exception("输入的插入位置不正确");
        }
        
        //Node[CurrentLength]=new Object();
        for(int i=CurrentLength;i>a;i--){
            Node[i]=Node[i-1];
            }
        Node[a]=node;
        CurrentLength++;
        
    }
public void delete(int a) throws Exception{ //删除元素
        
        if(a<0||a>CurrentLength){
            
            throw new Exception("输入的删除位置不正确");
        }
        
        //Node[CurrentLength]=new Object();
        for(int i=a;i<CurrentLength;i++){
            Node[i-1]=Node[i];
            }
    
         CurrentLength--;
        
    }
    public void ouprint() {    //输出线性表
        System.out.println("当前线性表中的元素为:");
        for (int i = 0; i < CurrentLength; i++) {
            System.out.print(Node[i]+"*");
        }
            System.out.print("当前长度为:"+CurrentLength);
            
    }
    
}
public class insert {
    public static void main(String[] args) throws Exception {
        LinList list=new LinList(20);
        Object insertObject;
        int len,locate;
        Scanner input=new Scanner(System.in);
        System.out.println("请输入线性表的长度");
        len=input.nextInt();
        System.out.println("请输入线性表的各个元素");
        for (int i = 0; i < len; i++) {
            insertObject=input.nextInt();
            list.add(insertObject);
        }
        System.out.println("请输入将要插入线性表的位置(从0开始算起)");
        locate=input.nextInt();
        System.out.println("请输入将要插入的元素");
        insertObject=input.nextInt();
        list.insert(locate,insertObject);
        System.out.println("第2个元素是:"+list.GetAnElement(2));
        System.out.println("请输入要删除的元素的位置(从一开始算起):");
        locate=input.nextInt();
        list.delete(locate);
        list.ouprint();
    }
    
    

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值