链表的Java实现(使用内部类作为指针的引用)

class Element {
	private String name;
	private Element next;

	public Element(String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	public void setNextElement(Element next) {
		this.next = next;

	}

	public Element getNextElement() {
		return this.next;
	}

}

public class LinkDemo {
	public static void main(String args[]) {
		Element root = new Element("根节点");
		Element elem1 = new Element("节点1");
		Element elem2 = new Element("节点2");
		Element elem3 = new Element("节点3");
		Element elem4 = new Element("节点4");

		root.setNextElement(elem1);
		elem1.setNextElement(elem2);
		elem2.setNextElement(elem3);
		elem3.setNextElement(elem4);

		print(root);

	}

	public static void print(Element elem) {
		if (elem != null) {
			System.out.print(elem.getName() + " --> ");
		}
		if (elem.getNextElement() != null) {
			print(elem.getNextElement());
		}
	}

}


你可能感兴趣的:(java,String,null,Class)