链表05-开发可用链表(判断某一个数据是否存在)
数据查询:public boolean contains(数据类型 变量)
判断某一个数据是否存在
在链表之中一定会保存有多个数据,那么基本的判断数据是否存在的方式,以String为例,循环链表中的内容,并且与要查询的数据进行匹配(euqals()),如果查找到了返回true,否则返回false
修改Link,增加contains()方法
public boolean contains(String data){ // 现在没有要查询的数据,要节点也不保存数据 if ( data == null || this.root == null ) { return false; //没有查询结果 } return this.root.containsNode(data); }
从根元素开始查询数据是否存在
修改Node类,增加containsNode()方法
// 第一次调用(Link): this = Link.root // 第二次调用 (Node) : this = Link.root.next public boolean containsNode(String data){ if (data.equals(this.data)){ // 当前节点数据为要查询数据 return true; //后面不再查询了 }else{ //当前节点数据不满足查询要求 if (this.next != null){ // 有后续节点 return this.next.containsNode(data); }else{ // 没有后续节点了 return false; // 没得查了 } } }
完整代码
class Link{ // 链表类,外部只能看这一个类 // 定义在内部,主要为Link类服务 private class Node{ // 定义的节点类 private String data; // 保存数据 private Node next; // 引用关系 public Node(String data){ this.data = data; } public void AddNode(Node newNode){ if(this.next == null){ // 当前的下一个节点为空 this.next = newNode; }else{ // 向后继续保存 this.next.AddNode(newNode); } } public void printNode(){ // 打印Node信息 System.out.println(this.data); if( this.next != null){ this.next.printNode(); } } // 第一次调用(Link): this = Link.root // 第二次调用 (Node) : this = Link.root.next public boolean containsNode(String data){ if (data.equals(this.data)){ // 当前节点数据为要查询数据 return true; //后面不再查询了 }else{ //当前节点数据不满足查询要求 if (this.next != null){ // 有后续节点 return this.next.containsNode(data); }else{ // 没有后续节点了 return false; // 没得查了 } } } // ===================以上为内部类============================ } private Node root; // 根结点 private int count = 0; // 保存元素的个数 public void add(String data){ // 假设不允许有null if (data == null){ return ; } Node newNode = new Node(data); // 要保存的数据 if (this.root == null){ // 如果当前没有根节点,则设置为根节点 this.root = newNode; // 保存根节点 }else{ // 存在根节点,则到下一节点找保存数据 this.root.AddNode(newNode); } this.count ++; // 每一次保存完成后数量加一 } public int size(){ // 取得保存的数据量 return this.count; } public boolean isEmpty(){ //判断链表是否为空 return this.root == null; } public boolean contains(String data){ // 现在没有要查询的数据,要节点也不保存数据 if ( data == null || this.root == null ) { return false; //没有查询结果 } return this.root.containsNode(data); } public void print(){ // 打印所有Node信息 this.root.printNode(); } } public class LinkDemo{ public static void main(String args[]){ Link all = new Link(); all.add("Hello"); all.add("World"); System.out.println(all.contains("Hello")); System.out.println(all.contains("ayou")); } }
本次使用的是String型数据,所以判断数据的时候 使用的是equals()方法,可是如果说现在要传递一个自定义对象呢?需要定义一个对象比较的方法(暂时将方法定义为compare())