栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

手写LinkedList

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

手写LinkedList

package _03;

import java.util.linkedList;

public class _3_10Demo {

//    linkedList: 底层由双向链表构成  查询效率低 增删效率高 线程不安全
    private Node first;
    private Node last;
    private int size;

    public void add(Object obj){
        Node node = new Node(obj);
        if(this.first==null){
            first = node;
            last  = node;
            size ++;
        }else{
            node.previous = last;
            node.next = null;
            last.next = node;
            last = node;
            size ++;
        }

    }

    public Object get(int index){
//        int n = 0;
//        Node node = first;
//        while(n  一半  则从后往前找last  如果index <一半  则从前往后找

        Node nd = getNode(index);
        return nd!=null ? nd.element:null;
    }


    public Node getNode(int index){
        if(index <0 || index >= size){
            throw new RuntimeException("index 不合法");
        }
        Node nd;
        if (index < size/2){
            nd = first;
            for(int i=0;iindex ;i--){
                nd = nd.previous;
            }
        }
        return nd;
    }

    public void remove(int index){

        Node nd = getNode(index);
        if (nd!=null){
            Node up =nd.previous;
            Node down =nd.next;
            if(up!=null){
                up.next = down;
            }
            if(down !=null){
                down.previous = up;
            }
            if(index == 0){
                first = down;
            }
            if(index == size-1){
                 last = up;
            }
            size--;
        }
    }

    public void add(int index,Object obj){
        Node nodeNew = new Node(obj);
        Node node = getNode(index);
        if(node!=null){
            Node up = node.previous;
            up.next = nodeNew;
            nodeNew.previous=up;
            node.previous=nodeNew;
            nodeNew.next=node;

            if(index==0){
                first = node;
            }
            if(index ==size -1){
                last = node;
            }
            size++;
        }

    }

    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        Node nd = first;
        while(nd !=null){
            sb.append(nd.element+",");
            nd = nd.next;
        }
        sb.setCharAt(sb.length()-1,']');
        return sb.toString();
    }

    public static void main(String[] args) {
        _3_10Demo ls = new _3_10Demo();
        System.out.println(ls.toString());
        System.out.println(ls.toString());

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/759305.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号