【问题标题】:LinkList for beginner初学者的链接列表
【发布时间】:2015-11-02 05:15:32
【问题描述】:
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 + "]";
              }
}

谁能帮我详细解释一下关于 else 语句的 addE() 方法?我理解 if 语句,但不是 else。我试图更好地理解它。谢谢!!!

【问题讨论】:

  • 根据您目前拥有的情况,如果您打算在末尾插入新的Node 时从头开始遍历列表,我看不出维护tail 指针的意义。请澄清您的问题,因为目前我认为您无法得到准确的答案。
  • @TimBiegeleisen 从我在代码中可以看到,tail 甚至没有在任何地方更新。它可能只是其他代码的产物。
  • @lc。我的意思是:在我们尝试回答之前,我们需要知道代码本身试图做什么。就目前而言,这个问题实际上要求重构解释该代码的作用。
  • @TimBiegeleisen 绝对是(以及我赞成您的评论的原因)。对不起,如果我的评论令人困惑;我只是指出了一个额外的观察结果。
  • @TimBiegeleisen 该代码实际上在我编译后给出了答案。添加前端和结束方法工作。我看不出代码为什么会这样工作的逻辑。

标签: linked-list singly-linked-list


【解决方案1】:

我认为代码应该如下:-

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++;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多