标签:lis bsp int() inpu 遍历 ret i++ creat import
question:
develop a recusive solution to the previous question.
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 current, int max_num) { if(current == null) { return max_num; } else { max_num = max_num > current.item ? max_num : current.item; return max(current.next, 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); Node current = head; if(current == null) { StdOut.println("the max num is " + 0); } else { int max_num = current.item; max_num = linklist.max(current, max_num); StdOut.println("the max num is " + max_num); } } }
标签:lis bsp int() inpu 遍历 ret i++ creat import
原文地址:https://www.cnblogs.com/w-j-c/p/9060302.html