链表

作者: Fighting_rain | 来源:发表于2018-07-11 12:32 被阅读0次

    单链表的添加和删除元素

    public class LinkedList<E> {
      private Node head;
      private int size;
    
      public LinkedList() {
          this.head = null;
          this.size = 0;
      }
    
    public void add(int index, E e) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("index 错误");
        }
    
        if (index == 0) {
            addFirst(e);
        } else {
            Node prev = head;
            for (int i = 0; i < index - 1; i++) {
                prev = prev.next;
            }
            Node node = new Node(e);
            node.next = prev.next;
            prev.next = node;
            size++;
        }
    
    }
    
    public void addFirst(E e) {
        Node node = new Node(e);
        node.next = head;
        head = node;
        size++;
    }
    
    public int getSize() {
        return size;
    }
    
    public boolean isEmpty() {
        return size == 0;
    }
    
    public E remove(int index) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("索引错误");
        }
        if (index == 0) {
            return removeFirst();
        } else {
            Node prev = head;
            for (int i = 0; i < index - 1; i++) {
                prev = prev.next;
            }
            Node removeNode = prev.next;
            prev.next = removeNode.next;
            removeNode.next = null;
            size--;
            return removeNode.e;
        }
    
    }
    
    public E removeFirst() {
        Node node = head;
        head = head.next;
        size--;
        return node.e;
    }
    
    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        Node node = this.head;
        while (node != null) {
            str.append(node.e);
            str.append("->");
            node = node.next;
        }
        str.append("NULL");
        return str.toString();
    }
    
    private class Node {
        public Node next;
        public E e;
    
        public Node(Node next, E e) {
            this.next = next;
            this.e = e;
        }
    
        public Node() {
            this(null, null);
        }
    
        public Node(E e) {
            this(null, e);
        }
    }
    }
    

    相关文章

      网友评论

          本文标题:链表

          本文链接:https://www.haomeiwen.com/subject/ixysxxtx.html