题目
编写一个方法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.有空再研究其他办法