数据结构-链表

public class LinkedDemo {
    private static class Node{
        int data;
        Node next;
        public Node(int data) {
            this.data = data;
        }
    }
    //头指针
    private  Node head;
    //尾指针
    private  Node last;
    //链表的长度
    private  int size;

    /**
     * 链表的插入
     * @param data 要插入的数据
     * @param index 要插入的位置
     */
    public  void insertList(int data,int index){
        if (index<0||index>size){
            throw new ArrayIndexOutOfBoundsException("链表越界,检查长度");
        }
        Node insertNode = new Node(data);
        if (size==0){
            //长度为0,头部插入
            head=insertNode;
            last=insertNode;
        }else if (index==size){
            //插入尾部
            last.next=insertNode;
            last=insertNode;
        }else {
            //插入中间
            Node preNode=getNode(index-1);
            Node nextNode=preNode.next;
            insertNode.next=nextNode;
            preNode.next=insertNode;
        }
        size++;
    }

    /**
     * 获取链表的一个节点
     * @param index 要获取节点的位置
     * @return Node
     */
    private  Node getNode(int index) {
        if (size==0||index>size){
            throw new ArrayIndexOutOfBoundsException("链表越界,检查长度");
        }
       Node temp = head;
        for (int i=0;i<index;i++){
            temp=temp.next;
        }
        size--;
        return temp;
    }

    private  void output(){
        Node temp = head;
        while (temp!=null){
            int data = temp.data;
            System.out.println(data+"");
            temp = temp.next;
        }
    }

    public static void main(String[] args) {
        LinkedDemo l = new LinkedDemo();
        l.insertList(1,0);
        l.insertList(2,1);
        l.insertList(3,2);
        l.insertList(4,2);
        l.output();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值