Ex1_3_28 递归返回节点最大值
  1. import edu.princeton.cs.algs4.StdIn;
  2. import edu.princeton.cs.algs4.StdOut;
  3. public class Ex1_3_28_maxNode<Item> {
  4. private class Node{
  5. Item item;
  6. Node next;
  7. }
  8. private Node head;
  9. private int N = 0;
  10. public boolean isEmpty(){
  11. return head == null;
  12. }
  13. public int size(){
  14. return N;
  15. }
  16. public void headInsert(Item item){
  17. Node node = head;
  18. head = new Node();
  19. head.item = item;
  20. head.next = node;
  21. N++;
  22. }
  23. public void headRemove(){
  24. if (isEmpty()) throw new RuntimeException("Queue underflow");
  25. else{
  26. head = head.next;
  27. N--;
  28. }
  29. }
  30. public int max(Node max, Node node){
  31. if(max == null) return 0;//空链表
  32. else if(node == null) return (int)max.item;//最大值
  33. else{
  34. if((int)max.item > (int)node.item){
  35. return max(max, node.next);
  36. }else return max(node, node.next);
  37. }
  38. }
  39. public static void main(String[] args){
  40. Ex1_3_28_maxNode m = new Ex1_3_28_maxNode();
  41. while (!StdIn.isEmpty()){
  42. int a = StdIn.readInt();
  43. m.headInsert(a);
  44. }
  45. StdOut.println(m.max(m.head,m.head.next));
  46. }
  47. }

要点:

  1. 链表实现,采用头插头删
  2. 递归初始接收head,head.next为参数;当开始head == null说明是空链表,返回0,当node == null说明链表已经遍历完毕,返回max