public class Linked
{
public static void main(String[] agrs){
Node root = new Node("火车头");
Node n1 = new Node("车厢1");
Node n2 = new Node("车厢2");
Node n3 = new Node("车厢3");
root.setNext(n1);
n1.setNext(n2);
n2.setNext(n3);
printNode(root);
}
public static void printNode(Node n){
while(n!=null){
System.out.print(n.getObject()+"\t");
n = n.getNext();
}
}
}
class Node
{
private Object o;
private Node next;
public Node(Object o){
this.o = o;
}
public void setNext(Node next){
this.next = next;
}
public Node getNext(){
return this.next;
}
public Object getObject(){
return this.o;
}
}
双向链表只需稍加改动
public class Linked
{
public static void main(String[] agrs){
Node root = new Node("火车头");
Node n1 = new Node("车厢1");
Node n2 = new Node("车厢2");
Node n3 = new Node("车厢3");
root.setNext(n1);
n1.setNext(n2);
n2.setNext(n3);
n3.setFront(n2);
n2.setFront(n1);
n1.setFront(root);
System.out.println(n2.getFront().getObject());
}
}
class Node
{
private Object o;
private Node front;
private Node next;
public Node(Object o){
this.o = o;
}
public void setNext(Node next){
this.next = next;
}
public Node getNext(){
return this.next;
}
public void setFront(Node front){
this.front = front;
}
public Node getFront(){
return this.front;
}
public Object getObject(){
return this.o;
}
}