码迷,mamicode.com
首页 > 其他好文 > 详细

1.3.21

时间:2018-05-19 13:03:05      阅读:152      评论:0      收藏:0      [点我收藏+]

标签: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");
        }
    }
}

 

1.3.21

标签:next   current   div   argument   list.sh   reads   als   equal   field   

原文地址:https://www.cnblogs.com/w-j-c/p/9059891.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!