LinkList适合初学者

时间:2015-11-02 05:15:33

标签: linked-list singly-linked-list

public class Node {

    int item;
    Node next;

    public Node() {

    item = 0;
    this.next = null;

    }
    public Node(int c) {

        item = c;
        next = null;

    }
    public Node(int c, Node next) {

    item = c;
    this.next = next;

    }

    }

public class List {

    Node head;
    Node tail;
    int size;

    public boolean isEmpty(){
        return head == null;
    }

    public int size(){
        return size;
    }

    public void addF(int i){

        head = new Node(i, head);
        size++;
    }

    public void addE(int i){

        if(head == null){

            Node s = new Node(i);
            tail = head;
        }else{

            Node s = head;
            while(s.next != null){
                s = s.next;
            }
            s.next = new Node(i);
            size++;
        }
    }

    public static void main(String[] args){

        List l = new List();
        l.addF(55);
        l.addF(56);
        l.addF(57);
        l.addE(54);
        l.addE(53);
        System.out.println(l.toString());
    }

     public String toString() {

         String result = "[  ";

         Node current = head;

         while (current != null) {

         result = result + current.item + "  ";

         current = current.next;
                }
                return result + "]";
              }
}

有人可以解释一下addE()方法对于else的详细说明吗?我理解是否陈述,但不是。我试图更好地理解它。谢谢!!!

1 个答案:

答案 0 :(得分:0)

我认为代码应该如下: -

public void addE(int i){

        if(head == null){

            Node s = new Node(i);
          head=s; //If the link list is empty then the first element(node) is the head
        }else{


            while(s.next != null){ //Traverse the entire linked list until you raech the tail
                s = s.next;
            }
            s.next = new Node(i);//add the new node
            size++;
        }
    }