简体   繁体   English

为什么它不打印? 链表

[英]why it doesn't print ? LinkedList

i have a problem that the method in LinkedList class don't print anything.. and i'm trying hard to know what's the problem i hope someone help我有一个问题,LinkedList 类中的方法不打印任何东西..我正在努力知道问题是什么,希望有人帮忙

the main class主班

    public static void main(String[] args) {
        LLnode a = new LLnode(10);
        LLnode b = new LLnode(20);
        LLnode c = new LLnode(50);
        LinkedList List1 = new LinkedList();
      
      List1.printAllNodes();
    }
}

LinkedList class链表类

public class LinkedList {
   
   private LLnode head;
   
  public LLnode gethead() {
        return this.head;
    }
    public void sethead(LLnode LLnode) {
        this.head = LLnode;
    }
   // Constructor
   public LinkedList() {
      head = null;
   }
   // Example Method to check if list is empty
   public boolean isEmpty() {
      return head == null;
   }
   
   public void printAllNodes() {
    LLnode helpPtr = head;
    while (helpPtr != null) {
        System.out.print(helpPtr.getdata() + " ");
        helpPtr = helpPtr.getnext();
   }

why it dosn't print i tried so hard为什么它不打印我这么努力

This is because you never add any nodes to your LinkedList.这是因为您从不向 LinkedList 添加任何节点。

Code could be as follows.代码可能如下。 Beware, nodes will be added at the beginning of list.请注意,节点将添加到列表的开头。

Main class:主要类:

public static void main(String[] args) {
    LLnode a = new LLnode(10);
    LLnode b = new LLnode(20);
    LLnode c = new LLnode(50);
    LinkedList List1 = new LinkedList();
    List1.add(a).add(b).add(c);
  
  List1.printAllNodes();
}

} }

LinkedList class:链表类:

public class LinkedList {
   
   private LLnode head;
   
  public LLnode gethead() {
        return this.head;
    }
    public void sethead(LLnode LLnode) {
        this.head = LLnode;
    }
   // Constructor
   public LinkedList() {
      head = null;
   }
   // Example Method to check if list is empty
   public boolean isEmpty() {
      return head == null;
   }
   
   public LinkedList add(LLnode node){
       LLnode oldHead = this.head();
       this.head = node;
       node.setNext(oldHead);
       return this;
   }

   public void printAllNodes() {
    LLnode helpPtr = head;
    while (helpPtr != null) {
        System.out.print(helpPtr.getdata() + " ");
        helpPtr = helpPtr.getnext();
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM