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

1.3.27

时间:2018-05-19 14:41:29      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:list   for   turn   int()   .sh   3.2   style   first   lis   

question:

write a method max() that takes a reference to the first node in a linked list as argument and returns the value of the maxnimun key in the list. assume that all keys are positive integers, and return 0 if the list is empty

answer:

import edu.princeton.cs.algs4.*;

public class Linklist
{
    private static class Node//节点
    {
        int item;
        Node next = null;
    }
    
     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 number of node " + i + ":");
            p2.item = StdIn.readInt();
            if(head == null)
            {
               head = p1 = p2;
            }
            else
            {
               p1.next = p2;
               p1 = p2;
            }
        }
        if(head != null)
        {
           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 int max(Node head)
    {
        if(head == null)
        {
            return 0;
        }
        Node current = head;
        int max_num;
        max_num = current.item;
        while(current != null)
        {
            if(current.item > max_num)
            {
                max_num = current.item;
            }
            current = current.next;
        }
        return max_num;
    }
    
    public static void main(String[] args)
    {
        Node head;
        int n;
        Linklist linklist = new Linklist();
        StdOut.println("input the length of linklist:(>0)");
        n = StdIn.readInt();
        head = linklist.create(n);
        linklist.show(head);
        int max_num = linklist.max(head);
        StdOut.println("the max number is " + max_num);
    }
    
}

 

1.3.27

标签:list   for   turn   int()   .sh   3.2   style   first   lis   

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

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