Custom singly linked list

background

We know that there are many structures in the array java inside, such as queues, stacks, etc., but these are the basic data structure of a data structure array, list or tree like configuration. So here own definition of an array of expansion, can be used to extend into the stack or queue.

public class UniLink<E> {

    //链表头结点
    private Node head;
    //链表元素个数
    private int size;


    //使用内部类定义元素节点
    private class Node {
        //节点数据
        private E e;
        //下一个节点指针
        private Node next;
        public Node(){};

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }
    }

    //按索引位置添加元素,链表不存在索引,此处索引是指链表中的位置
    public void add(int index,E e) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("索引异常");
        }
        if (index == 0) {
            head = new Node(e, null);
        } else {
            Node temp = head;
            for (int i = 0; i < index-1; i++) {
                temp = temp.next;
            }
            temp.next = new Node(e, temp.next);
        }
        size++;
    }

    //添加到头部
    public void addFirst(E e) {
        add(0,e);
    }

    //添加到尾部
    public void addLast(E e) {
        add(size, e);
    }

    //根据索引位置删除元素
    public void remove(int index) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("索引异常");
        }
        if (index == 0) {
            head = null;
        } else {
            Node temp = head;
            for (int i = 0; i < index - 1; i++) {
                temp = temp.next;
            }
            temp.next = temp.next.next;
        }
        size--;
    }
    
    //根据元素删除    
    public void removeEle(E e) {
        if (null == head) {
            return;
        }
        if (head.e.equals(e)) {
            head = head.next;
        } else {
            Node temp = head;
            for (int i = 0; i < size - 2; i++) {
                if (temp.next.e.equals(e)) {
                    temp.next = temp.next.next;
                }
                temp = temp.next;
            }
        }
        size--;
    }



    @Override
    public  String toString() {
        StringBuilder sbr = new StringBuilder();
        Node temp = head;
        for (int i = 0; i < size; i++) {
            sbr.append(temp.e);
            if (i < size - 1) {
                sbr.append("->");
            }
            temp = temp.next;
        }
        return sbr.toString();
    }

   
}

 

Guess you like

Origin blog.csdn.net/ly853602/article/details/93772654