链表的头插,尾插,按指定位置插入(java实现)

链表的java实现

链表是一种物理结构上的非连续,非顺序的存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的。
对于单项不带头的非循环链表来说,下面是它的结构图。
无头单项非循环链表
下面是对这种链表的 头插、尾插和按照指定位置插入

public class MyLinkedList{
   //内部类
    class Node{
        private int data;
        private Node next;
        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
    private Node head;
    public MyLinkedList() {
        this.head = null;
    }
//头插法
    public void addFirst(int data) {
        Node node=new Node(data);
        if (this.head==null){
            this.head=node;
        }else{
            node.next=this.head;
            this.head=node;
        }
    }
//尾插法
    public void addLast(int data) {
        Node node=new Node(data);
        Node cur=this.head;
        if (this.head==null){
            this.head=node;
        }else{
            while(cur.next!=null){
                cur=cur.next;
            }
            cur.next=node;
        }
    }
//按照坐标进行插入
    private Node search(int index){
        checkIndex(index);
        int count=0;
        Node cur=this.head;
        for (int i = 0; i <index-1 ; i++) {
            cur=cur.next;
            count++;
        }
        return cur;
    }
    private void checkIndex(int index){
        if (index<0||index>getLength()){
            throw new UnsupportedOperationException("位置不合法");
        }
    }
    public boolean addIndex(int index, int data) {
        if (index==0){
            addFirst(data);
            return true;
        }
        Node node=new Node(data);
        Node cur=search(index);
        node.next=cur.next;
        cur.next=node;
        return false;
    }

下面是对头插、尾插、按照指定位置插入的一个测试实现

public class TestLinkedList {
    public static void main(String[] args) {
        MyLinkedList myLinkedList=new MyLinkedList();
        myLinkedList.addFirst(1);
        myLinkedList.addFirst(2);
        myLinkedList.addFirst(3);
        myLinkedList.addFirst(4);
        myLinkedList.display();
        myLinkedList.addLast(4);
        myLinkedList.addLast(3);
        myLinkedList.addLast(2);
        myLinkedList.addLast(1);
        myLinkedList.display();
        myLinkedList.addIndex(0,0);
        myLinkedList.addIndex(1,1);
        myLinkedList.display();

    }
}

下面是其结果:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值