我刚刚创建了自定义节点类并创建了一个链表,但是当我打印列表中的数据时,数据是向后打印的。 我以为我正确设置了指针并在列表开头添加新节点。 但显然编译器不这么认为。我花了一段时间才终于理解了指针,但我想我并没有像我想象的那么理解。
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 ;
}
}
public class Main {
public static Node head;
public static void main (String args [])
{
add("P1" , "2");
add("P2", "3");
add("P3", "4");
add("P4", "4");
printList();
}
// add data to nodes
public static void add(String d, String c)
{
Node temp = null;
if (head == null)
{
head = new Node(d, c, null);
}
else
{
temp=head;
head= new Node(d, c, temp);
}
}
// print node data
public static void printList()
{
while (head != null)
{
System.out.println(head);
head=head.next;
}
}
}
您的列表是向后打印的,因为稍后创建的节点放置在列表的顶部,而不是后面。 即
head -> Node1
成为
head -> Node2 -> Node1
然后
head -> Node3 -> Node2 -> Node1
您在printList
中的迭代是可以的。 在add
中,您需要找到最后一个Node
(next
null
)并将新Node
放置在那里,而不是将新Node
放在头部。 即
head -> 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);
}
你所描述的行为实际上正是LinkedList应该如何工作的。正如 rgettman 指出的那样,当您在 LinkedList 上使用 add 方法时,您会添加到列表的头部。问题是,当您通过设置 head = head.next 从 LinkedList 中删除时,您也会从 head 中删除。
如果仍然不清楚,请查看此动画: http://www.cs.usfca.edu/~galles/visualization/StackLL.html 尝试将几个整数推送到堆栈,然后弹出它们。这就是您的链表的工作方式。
解决此问题的一种方法是将所有值粘在一起,以便在打印它们之前将它们按顺序排列。
public static void printList()
{
String toPrint = "";
while (head != null)
{
toPrint = head + "n" + toPrint;
head = head.next;
}
System.out.println(toPrint);
}
rgettman 是对的,当你将一个元素添加到链表时,你首先添加到
//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;
}
}