算法-第四版-练习1.3.27解答

题目

编写一个方法max(),接受一个链表的首结点作为参数,返回链表中键最大的节点的值。假设所有键均为正整数,如果链表为空则返回0。

分析

方法的参数为Node
假定键为正整数,那么max先等于0
不考虑链表为空
先接受Node为Current
用while循环不断遍历Current且得到current的下一个值
判断current.item的值和max 取得最大值.返回
main方法里面要生成一个Node

java代码

package hk13;

import edu.princeton.cs.algs4.In;

import java.util.Iterator;

/**
 * @description: ${description}
 * @create: 2019-02-19
 **/
public class W_1_3_27<Item> implements Iterable {
    private static class Node<Item> {//改成静态的
        Item item;
        Node next;
    }

    private Node first;//栈顶,最近添加元素,也是个类,有两个属性
    private Node last;
    private int n;//元素数量,类似指针

    public void push(Item item) {
        Node old = first;
        first = new Node();
        first.item = item;
        first.next = old;
        n++;
    }

    public Item pop() {
        n--;
        Item item = (Item) first.item;//多了个强转 为什么呢???
        first = first.next;
        return item;
    }
    public static int max(Node<Integer> node){
        Node<Integer> current=node;
        int max= 0;
        while (current!=null){
            int a =  current.item;
            if(max<a){
                max=a;
            }
            current=current.next;
        }
        return max;
    }

    public static void printList(W_1_3_26 a) {
        for (Object o : a
        ) {
            System.out.print(o+" ");
        }
        System.out.println();
    }

    public int size() {
        return n;
    }

    public boolean isEmpty() {
        return n == 0;
    }

    @Override
    public Iterator iterator() {
        return new ListIterator();
    }

    private class ListIterator implements Iterator<Item> {
        private Node current = first;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            Item item = (Item) current.item;
            current = current.next;
            return item;
        }

        @Override
        public void remove() {
            //blank
        }

    }

    public static void main(String[] args) {
        Node<Integer> a1=new Node<Integer>();
        a1.item=1;
        Node<Integer> a2=new Node<Integer>();
        a2.item=2;
        Node<Integer> a3=new Node<Integer>();
        a3.item=3;
        Node<Integer> a4=new Node<Integer>();
        a4.item=5;
        Node<Integer> a5=new Node<Integer>();
        a5.item=4;
        a1.next=a2;
        a2.next=a3;
        a3.next=a4;
        a4.next=a5;
        int max = max(a1);
        System.out.println(max);
    }
}

运行结果

在这里插入图片描述

心得

1.这种传入参数Node的比较不好感觉.不如传入链表数据
2.其他比较简单
3.有空再研究其他办法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值