我正在尝试在最后一个链接列表中添加数据。这是我的代码。 这是我的链接列表类:
public class LinkedList {
Node head;
private static class Node {
int data;
Node pointer;
public Node(int data) {
this.data=data;
pointer=null;
}
}
此方法用于在最后添加数据。
public void append(int new_data){
Node new_node=new Node (new_data);
if (head==null){
head=new Node(new_data);
}
Node last_node=head;
new_node.pointer=null;
while (last_node.pointer !=null){
last_node=last_node.pointer;
last_node.pointer=new_node;
}
}
这种方法是打印数据。
public void printData(){
Node print_Node;
print_Node=head;
while (print_Node !=null){
System.out.print(print_Node.data+" ");
print_Node=print_Node.pointer;
}
}
public static void main(String[] args) {
LinkedList obj=new LinkedList();
obj.append(10);
obj.append(100);
obj.printData();
}
}
我的代码中的问题在哪里?它只打印10.
答案 0 :(得分:0)
你的问题在这里:
while (last_node.pointer !=null){
last_node=last_node.pointer;
last_node.pointer=new_node; // this line ... bad!
您正在使用last_node来迭代列表中的所有节点。 而你正在迭代;您正在设置所有这些节点的指针...指向新创建的节点。但是当你到达列表末尾时,你应该只做一次!
不确定为什么会让您第一次进入;但是,你追加的代码绝对不正确。
答案 1 :(得分:0)
尝试这个
public class linked_list {
Node head;
private static class Node
{
int data;
Node pointer;
public Node(int data)
{
this.data = data;
pointer = null;
}
}
public void append(int new_data)
{
Node new_node = new Node(new_data);
//new_node.pointer = null; No need to set pointer to null as it is already null in your constructor.
if (head == null)
{
head = new Node(new_data);
}
Node last_node = head; // Its okay To not change head , good practise.
while (last_node.pointer != null)
{
last_node = last_node.pointer;
}
// I think here was the error, your the linked list was not adding only one element , Because while loop
// got terminated just it reaches null i.e not executing the below line.
// So put it after while loop, wen you have reached the NULL.
last_node.pointer = new_node; // line ERROR
}
public void printData(){
Node print_Node;
print_Node=head;
while (print_Node !=null){
System.out.print(print_Node.data+" ");
print_Node = print_Node.pointer;
}
}
public static void main(String[] args)
{
linked_list obj=new linked_list();
obj.append(10);
obj.append(100);
obj.append(898);
obj.append(8334);
obj.append(118334);
obj.append(833400);
obj.append(83340043);
obj.printData();
}
}