您的位置:首页 > 编程语言 > Java开发

Java的单向链表和内部类的结合使用

2012-11-01 17:23 357 查看
class Link
{
	// 节点
	class Node
	{
		public String name;
		public Node next;

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

		public Node getNext()
		{
			return next;
		}

		public void setNext(Node next)
		{
			this.next = next;
		}

		// 向下一个节点添加节点
		public void addNode(Node node)
		{
			if (this.next == null)
			{
				next = node;
			}
			else
			{
				next.addNode(node);
			}
		}

		// 打印所有节点
		public void printNode()
		{
			System.out.print(this.name + "---->");
			if (this.next != null)
			{
				this.next.printNode();
			}
		}

		// 查询某个节点
		public boolean searchNode(String name)
		{
			if (this.name.equals(name))
			{
				return true;
			}
			else
			{
				return this.next.searchNode(name);
			}
		}

		// 删除某个节点
		public void deleteNode(Node parentNode, String name)
		{
			if (this.name.equals(name))
			{
				parentNode.next = this.next;
			}
			else
			{
				this.next.deleteNode(this, name);
			}
		}
	}
	// 根节点
	private Node root;

	// 添加节点
	public void add(String name)
	{
		Node newNode = new Node(name);
		if (root == null)
		{
			root = newNode;
		}
		else
		{
			root.addNode(newNode);
		}
	}

	// 打印节点
	public void print()
	{
		if (this.root != null)
		{
			this.root.printNode();
		}
	}

	// 查询节点
	public boolean search(String name)
	{
		if (name != null)
		{
			return this.root.searchNode(name);
		}
		else
		{
			return false;
		}
	}

	// 删除节点
	public void delete(String name)
	{
		if (this.search(name))
		{
			if (this.root.name.equals(name))
			{
				if (this.root.next != null)
				{
					this.root = this.root.next;
				}
				else
				{
					this.root = null;
				}
			}
			else
			{
				this.root.deleteNode(root, name);
			}
		}
	}
}
public class NodeTest
{
	public static void main(String[] args)
	{
		Link link = new Link();
		link.add("根节点");
		link.add("第一节点");
		link.add("第二节点");
		link.add("第三节点");
		link.add("第四节点");
		link.add("第五节点");
		link.print();
		System.out.println();
		 System.out.println(link.search("第一节点"));
		System.out.println();
		link.delete("第三节点");
		link.print();
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: