标签: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); } }
标签:list for turn int() .sh 3.2 style first lis
原文地址:https://www.cnblogs.com/w-j-c/p/9060172.html