我正在学习Java链接列表,并编写了一些示例代码供练习。基本上是一个单链链表。代码工作正常,但它反转输出。那就是打印出科里,乔和汤姆,我希望输出是汤姆,乔和科里。汤姆是第一个节点。我该如何去做,或者这就是一个链接列表的工作方式。也就是说,它总是反转输出?
public class LinkedList {
public String name;
public LinkedList next;
public LinkedList(String name)
{
this.name = name;
this.next = null;
}
public String toString()
{
return name;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Linked l = new Linked();
l.insert("tom");
l.insert("joe");
l.insert("cory");
l.print();
}
}
class Linked
{
LinkedList first;
public Linked()//initialize
{
this.first = null;
}
public void insert(String name)
{
LinkedList g = new LinkedList(name);
g.next = first;
first = g;
}
//checks if the list is empty
public boolean isEmpty()
{
return (first ==null);
}
public void print() //displays the list
{
LinkedList t = first;
while(t!=null)
{
System.out.println(t);
t = t.next;
}
}
}
发布于 2014-10-30 18:26:53
在LinkedList开头插入。如果要添加,则在最后一个节点之后插入新节点。你需要一个尾巴参考。
public String name;
public LinkedList next;
public LinkedList(String name)
{
this.name = name;
this.next = null;
}
public String toString()
{
return name;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Linked l = new Linked();
l.insert("tom");
l.insert("joe");
l.insert("cory");
l.print();
}
}
class Linked
{
LinkedList first;
LinkedList tail;
public Linked()//initialize
{
this.first = null;
this.tail = first;
}
public void insert(String name)
{
LinkedList g = new Test(name);
if(isEmpty())
{
first = g;
tail = first;
}
else
{
tail.next = g;
tail = g;
}
}
//checks if the list is empty
public boolean isEmpty()
{
return (first ==null);
}
public void print() //displays the list
{
LinkedList t = first;
while(t!=null)
{
System.out.println(t);
t = t.next;
}
}
如果您注意到,我添加了一个尾引用,而不是在开始时插入新对象,而是将它附加到LinkedList的末尾。您可以更改要添加的方法名。事实上,您可以有两个方法,保持您的is...then添加我的新方法插入,但调用它,添加方式,您可以在开始插入或添加到LinkedList结束。
发布于 2014-10-30 18:35:13
正如@brso05 05所指出的,您正在将值插入头部,而不是将其插入到尾部。
那是
tom
joe -> tom
cory -> joe -> tom
相反,你应该把它插入到尾巴上,就像这样
public void insert(String name)
{
if(first==null)
{
LinkedList g = new LinkedList(name);
g.next = null;
first = g;
} else {
LinkedList g = new LinkedList(name);
if (first.next==null) {
g.next = null;
first = g;
return;
}
LinkedList l=first.next;
for(;l!=null;l=l.next){
if(l.next==null) {
l.next = g;
g.next = null;
break;
}
}
}
}
这不是一个很好的解决办法,应该是临时的。
https://stackoverflow.com/questions/26660554
复制相似问题