方法实现:
//1.3.21 /** * find if some node in the list has key as its item field * * @param list the linked list of T * @param key the T key * * @return {@code true} some node exists. * {@code false} no node exist */ public static <T> boolean find(LinkedList<T> list, T key) { for(T s : list) { if(s.equals(key)) return true; } return false; }
测试用例:
package com.qiusongde.linkedlist; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; public class Exercise1321 { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); while(!StdIn.isEmpty()) { String s = StdIn.readString(); list.insertAtBeginning(s); StdOut.println("insertAtBeginning success: " + s); StdOut.println(list); } String key = "qiu"; StdOut.println("find " + key + " :" + LinkedList.find(list, key)); key = "not"; StdOut.println("find " + key + " :" + LinkedList.find(list, key)); } }
输入数据:
to
be
or
not
to
输出结果:
insertAtBeginning success: to to insertAtBeginning success: be be to insertAtBeginning success: or or be to insertAtBeginning success: not not or be to insertAtBeginning success: to to not or be to find qiu :false find not :true