码迷,mamicode.com
首页 > 其他好文 > 详细

自己实现LinkedList

时间:2019-12-14 19:16:03      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:sys   rem   tostring   link   null   uil   col   override   color   

public class MyLinkedList<E> {

    private Node first;

    private int size;

    public int size(){
        return size;
    }

    @Override
    public String toString() {
       if(size == 0){
           return  "[]";
       }else{
           StringBuilder sb = new StringBuilder("[");
           Node current = first;
           while (current != null){
               sb.append(current.value).append(",");
               current = current.next;
           }
           sb.replace(sb.length() - 1, sb.length(), "]");
           return sb.toString();
       }
    }

    public static void main(String[] args) {
        MyLinkedList list = new MyLinkedList();
        list.addFirst("python").addFirst("java").addFirst("hello").addFirst("php");
        System.out.println(list);
        list.removeFirst();
        System.out.println(list);
        System.out.println(list.contains("python"));

    }
    public E removeFirst(){
        if(size == 0){
            return  null;
        }else {
            Node<E>  temp  =  first;
            first = temp.next;
            size--;
            return  temp.value;
        }
    }

    public   boolean contains(E e){
        Node current = first;
        while(current != null){
            if(current.value == e ){
                return true;
            }
            current = current.next;
        }
        return false;
    }

    public MyLinkedList addFirst(E e){
        Node newNode = new Node(e);
        newNode.next = first;
        first = newNode;
        size++;
        return this;
    }

    private  static  class  Node<E>{
        private E value;
        private Node next;

        Node(E value){
            this.value = value;
        }

        @Override
        public String toString() {
            return  value == null?"null":value+"";
        }
    }
}

自己实现LinkedList

标签:sys   rem   tostring   link   null   uil   col   override   color   

原文地址:https://www.cnblogs.com/moris5013/p/12040389.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!