Java 自定义链表数据打印backword
我刚刚创建了我的自定义节点类并创建了一个链表,但是当我打印列表中的数据时,数据是反向打印的。我想我设置了正确的指针,并在列表的开头添加了新节点。但显然编译器的想法是相反的。我花了一段时间才最终理解指针,但我想我理解得不如我想的那么好Java 自定义链表数据打印backword,java,data-structures,Java,Data Structures,我刚刚创建了我的自定义节点类并创建了一个链表,但是当我打印列表中的数据时,数据是反向打印的。我想我设置了正确的指针,并在列表的开头添加了新节点。但显然编译器的想法是相反的。我花了一段时间才最终理解指针,但我想我理解得不如我想的那么好 public class Node { public String data; public String cat; public Node next; public Node (String data, String cat, Node next){
public class Node {
public String data;
public String cat;
public Node next;
public Node (String data, String cat, Node next){
this.data=data;
this.cat=cat;
this.next=next;
}
public Node() {
}
public String toString()
{
return "Patient: " + data + " Category: " +cat ;
}
}
}您的列表正在向后打印,因为稍后创建的节点将放在列表的开头,而不是后面。即
head -> Node1
head -> Node1
变成
head -> Node2 -> Node1
head -> Node1 -> Node2
然后
head -> Node3 -> Node2 -> Node1
您在printList中的迭代是正常的。在add中,您需要找到next为null的最后一个节点并将新节点放置在那里,而不是将新节点放置在头部。即
变成
head -> Node2 -> Node1
head -> Node1 -> Node2
将列表不为空时的else更改为:
else
{
temp = head;
// Get last item
while (temp.next != null)
{
temp = temp.next;
}
// Point old last item to *new* last item
temp.next = new Node(d, c, null);
}
当您将元素添加到在第一个位置添加的链接列表时,Targetman是对的
//element1->null
//add(element2)
//element2->element1->null
您可以迭代搜索null并在最后一个位置插入,类似这样
public static void add(String d, String c)
{
Node temp = null;
if (head == null)
{
head = new Node(d, c, null);
}
else
{
temp=head;
while(temp!=null){ //search last element
temp=temp.next();
}
temp.next= new Node(d, c, null); //the new element it's after the last
}
}
您还可以创建一个名为Node lastNode的变量,并将最后一个节点保存在此处,这样做不必循环,更高效的算法。比如:
public class Node {
public Node lastNode;
...
}
在主课堂上
public static void add(String d, String c)
{
Node temp = null;
if (head == null)
{
head = new Node(d, c, null);
lastNode=head;
}
else
{
Node newnode= new Node(d,c,null);
lastNode.next=newnode;
lastNode= newnode;
}
}
您所描述的行为实际上正是LinkedList的预期工作方式。正如Rgetman所指出的,当您在LinkedList上使用add方法时,您将添加到列表的开头。问题是,当您通过设置head=head从LinkedList中删除时。接下来,您还将从head中删除 如果仍然不清楚,请查看此动画:尝试将几个整数推入堆栈,然后弹出它们。这就是链接列表的工作方式 解决此问题的一种方法是将所有值粘在一起,以便在打印之前将它们按顺序排列
public static void printList()
{
String toPrint = "";
while (head != null)
{
toPrint = head + "\n" + toPrint;
head = head.next;
}
System.out.println(toPrint);
}
您需要从尾部指针添加到列表中。如果只使用头指针,它的行为将类似于堆栈。@bimm3rBoy我在答案中添加了代码以添加到列表的末尾。谢谢,我终于得到了它!