读书人

Link List 的节点数据输出有关问题

发布时间: 2011-12-24 23:03:24 作者: rapoo

Link List 的节点数据输出问题
我建立了一个链表,每个节点保存了两个实数。
用的是object 方法。
[code]
class ListNode
{
// package access members; List can access these directly
Object Data;
ListNode nextNode;

// constructor creates a ListNode that refers to object
ListNode( Object object )
{
this( object, null );
} // end ListNode one-argument constructor

// constructor creates ListNode that refers to
// Object and to next ListNode
ListNode( Object object, ListNode node )
{
Data = object;
nextNode = node;
} // end ListNode two-argument constructor
[/code]
这两个实数,我用了个class Data
[code]
public class Data
{
private double x;
private double y;
public Data(double x,double y)
{
x=this.x;
y=this.y;
}
[/code]
主程序是这样的
[code]
public class ListTest
{
public static void main( String args[] )
{
List list = new List(); // create the List container
Data x1 =new Data(9,-9);

list.insertAtFront( x1 );
list.print();
Data x2 =new Data(8,-8);
list.insertAtFront( x2 );
list.print();
...
}
[/code]
我的问题是,怎么把链表里的数据输出来。
在传统的链表操作中,通常是保存一个数据,这样非常好输出,只用一个语句就可。如
[code]
public void print()
{
if ( isEmpty() )
{
System.out.printf( "Empty %s\n ", name );
return;
} // end if

System.out.printf( "The %s is: ", name );
ListNode current = firstNode;



// while not at end of list, output current node 's data
while ( current != null )
{
System.out.printf( "%.2f ", current.Data);
current = current.nextNode;
} // end while

System.out.println( "\n " );
} // end method print
[/code]
但现在Data里存有两个数据,System.out.printf( "%.2f ", current.Data);输不出来,请问有没有什么好办法?
焦急等待中,谢谢!

[解决办法]
public class Data
{
private double x;
private double y;
public Data(double x,double y)
{
x=this.x;
y=this.y;
}
}

给这个类加个结果输出函数不就可以了。
比如print(),或者toString(),输出的时候只要 current.Data.toString()

[解决办法]
System.out.printf( "%.2f ", current.Data);

里面有printf这个函数么?我没看到你写的啊。。
[解决办法]
list.print();

这个方法的实现是什么

public class Data
{
private double x;
private double y;
public Data(double x,double y)
{
x=this.x;
y=this.y;
}
public String toString() {
System.out.println(x+ " "+y);
}
}
[解决办法]
我要用这两个数,但不在 class Data 里,因为在建立了链表后,我还有另外一个method.取出来数据从链表中。
public Object removeFromFront() throws EmptyListException
{
if ( isEmpty() ) // throw exception if List is empty
throw new EmptyListException( name );

Object removedItem = firstNode.Data; // retrieve data being removed

// update references firstNode and lastNode
if ( firstNode == lastNode )
firstNode = lastNode = null;
else
firstNode = firstNode.nextNode;

return removedItem; // return removed node data
}

如果要用removedItem里的两个数,怎么用函数来表达,头脑一下僵住了,想不出来。

读书人网 >J2SE开发

热点推荐