标签:next current div argument list.sh reads als equal field
question:
write a method find() that takes a linked list and a string key as arguments and returns true if some node in the list has the key as its item field, false otherwise.
answer:
import edu.princeton.cs.algs4.*; public class Linklist { private static class Node { String item; Node next; } public Node create(int n) { Node head = null; Node p1 = head; Node p2; for(int i = 0; i < n; i++) { p2 = new Node(); StdOut.println("input the string of node " + i + ":"); p2.item = StdIn.readString(); if(head == null) { head = p1 = p2; } else { p1.next = p2; p1 = p2; } } p1.next = null; return head; } public void show(Node head) { Node current = head; while(current != null) { StdOut.print(current.item + "\t"); current= current.next; } StdOut.print("\n"); } public boolean find(Node head, String key) { Node current = head; if(current == null) { return false; } while(current != null) { if(current.item.equals(key)) { return true; } current = current.next; } return false; } public static void main(String[] args) { int n; Node head; Linklist linklist = new Linklist(); StdOut.println("input the length of linklist:(>0)"); n = StdIn.readInt(); head = linklist.create(n); linklist.show(head); StdOut.println("input the string to find:"); String key = StdIn.readString(); boolean ans = linklist.find(head, key); if(ans == true) { StdOut.println("find"); } else { StdOut.println("not find"); } } }
标签:next current div argument list.sh reads als equal field
原文地址:https://www.cnblogs.com/w-j-c/p/9059891.html