Java自学-集合之单向链表

使用java语言模拟单向链表。
设计节点类:添加节点,删除节点,查询节点,输出节点
需要的方法:
1.可以添加节点
2.可以删除节点
3.可以查看节点是否存在
4.输出节点的数据

class Linted{
	
	//成员内部类
	class Node{
		private String name;
		private Node next;
		
		public Node(String name){
			this.name = name;
		}
		
		//添加节点
		public void add(Node node) {
			if(this.next == null) {
				this.next = node;
			}else {
				this.next.add(node);
			}
		}
		
		public void print() {
			System.out.print(this.name + "-->");
			if(this.next != null) {
				this.next.print();
			}
		}
		
		public boolean search(String string) {
			if(this.name.equals(string)) {
				return	true;
			}else {
				if(this.next != null) {
					return this.next.search(string);
				}else {
					return false;
				}
			}
		}
		
		public void delete(String string) {
			if(this.next.name.equals(string)) {
				this.next = this.next.next;
			}else{
				this.next.delete(string);
			}
		}
		
	}
	
	private Node root;
	
	//创建根节点
	public void add(String string) {
		Node node = new Node(string);
		if(this.root == null) {
			this.root = node;
		}else {
			this.root.add(node);	//上面的代码只是在链表没有节点时创建根(头)节点,要添加节点需要用Node的add()方法
		}
	}
	
	//打印节点,只要节点不为空,就调用Node的print()方法
	public void print() {
		if(this.root != null) {
			this.root.print();
		}
	}
	
	////查看节点,只要节点不为空,就调用Node的search()方法
	public boolean search(String string) {
		if(this.root != null) {
			return this.root.search(string);
		}else {
			return false;
		}
	}
	
	//删除某个节点
	public void delete(String string) {
		if(this.search(string)) {		//遍历是否有这个元素
			if(this.root.name.equals(string)) {		//判断name是否等于string,不是则调用Node的delete()方法,判断下一个
				if(this.root.next != null) {		//找到了这个元素,判断这个元素指向是否为空,若为空,则把这个节点的前一个节点的指向为空
					this.root = this.root.next;		//不为空就把第三个节点的内存地址赋给第一个节点
				}else {
					this.root = null;
				}
			}else {
				this.root.delete(string);
			}
		}
	}
	
}

public class LintedText02 {
	public static void main(String[] args) {
		Linted lin = new Linted();
		
		lin.add("a");
		lin.add("b");
		lin.add("c");
		lin.add("d");
		lin.add("e");
		lin.print();
		
		System.out.println();
		System.out.println(lin.search("q"));
		
		lin.delete("b");
		lin.delete("a");
		
		lin.print();
		
	}
}

有什么不懂的,或者有什么不同的意见欢迎讨论啊!

发布了3 篇原创文章 · 获赞 0 · 访问量 16

猜你喜欢

转载自blog.csdn.net/weixin_44317777/article/details/105311528