自己实现LinkedList集合add,get,remove

自己实现LinkedList集合add,get,remove

  • Node类

    public class Node {

    ....public Node previous;

    ....public Object obj;

    ....public Node next;

    ....

    ....public Node()

    ....{

    ........

    ....}

    ....public Node(Node previous, Object obj, Node next) {

    ........super();

    ........this.previous = previous;

    ........this.obj = obj;

    ........this.next = next;

    ....}

    ....public Node getPrevious() {

    ........return previous;

    ....}

    ....public void setPrevious(Node previous) {

    ........this.previous = previous;

    ....}

    ....public Object getObj() {

    ........return obj;

    ....}

    ....public void setObj(Object obj) {

    ........this.obj = obj;

    ....}

    ....public Node getNext() {

    ........return next;

    ....}

    ....public void setNext(Node next) {

    ........this.next = next;

    ....}

    }

    MyLinkedList类

    public class MyLinkedList {

        private Node first;

        private Node last;

        private int size=0;

       

        public void add(Object obj)

        {

        ....Node n = new Node();

        ....if (first == null)

        ....{

        ........n.setPrevious(null);

        ........n.setObj(obj);

        ........n.setNext(null);

        ........

        ........first = n;

        ........last = n;

        ....}

        ....else

        ....{

        ........n.setPrevious(last);

        ........n.setObj(obj);

        ........n.setNext(null);

        ........

        ........last.setNext(n);

        ........last = n;

        ....}

        ....size++;

        }

        public Object get(int index)

        {

    ........Node ntemp = node(index);

        ....return ntemp.getObj();

        }

       

        public void remove(int index)

        {

        ....Node ntemp = node(index);

        ....if(ntemp != null)

        ....{

        ........Node up = ntemp.getPrevious();

        ........Node down = ntemp.getNext();

        ........up.setNext(down);

        ........down.setPrevious(up);

        ....}

        }

       

        public Node node(int index)

        {

        ....Node nodeTemp = null;

        ....if(first != null)

        ....{

        ........nodeTemp = first;

        ........for(int i=0 ; i

        ........{

        ............nodeTemp = nodeTemp.getNext();

        ........}

        ....}

        ....return nodeTemp;

        }

       

        public int size()

        {

        ....return size;

        }

       

        public static void main(String[] args) {

        ....MyLinkedList linkList = new MyLinkedList();

        ....linkList.add("aa");

        ....linkList.add("bb");

        ....linkList.add("cc");

        ....linkList.remove(1);

        ....System.out.println("0:"+linkList.get(1));

        }

    }

你可能感兴趣的:(java)