Java 函数查找符号表中的第二大键
因此,我正在编写一个函数,它将使用一个链表实现在一个未排序的符号表中查找第二大键,到目前为止,我的代码工作不正常,我想知道是否有人有任何提示谢谢Java 函数查找符号表中的第二大键,java,linked-list,key-value,symbol-table,Java,Linked List,Key Value,Symbol Table,因此,我正在编写一个函数,它将使用一个链表实现在一个未排序的符号表中查找第二大键,到目前为止,我的代码工作不正常,我想知道是否有人有任何提示谢谢 public Key secondLargestKey () { if(first == null) return null; if(size()<=1) return null; Node secondMax=null; Node Max=first;
public Key secondLargestKey () {
if(first == null) return null;
if(size()<=1) return null;
Node secondMax=null;
Node Max=first;
for (Node pointer=first.next;pointer.next!=null;pointer=pointer.next) {
if(Max.key.compareTo(pointer.key)<=0) {
secondMax=Max;
Max=pointer.next;
}
else {
secondMax=Max.next;
Max=pointer;
}
}
return Max.key;
}`
您的代码几乎是正确的。
for
循环中的终止条件需要检查指针=null,不是指针。下一步=空
。此外,如果pointer.key
小于Max
,则需要将其与secondMax
进行比较,如果大于则接受,或者secondMax
为null
(即尚未设置)
以下是一些代码供参考:
static <E extends Comparable<E>> E secondMax(Node<E> head)
{
if(head == null) return null;
E max2 = null;
E max1 = head.key;
for(Node<E> curr=head.next; curr!=null; curr=curr.next)
{
if(curr.key.compareTo(max1) >= 0)
{
max2 = max1;
max1 = curr.key;
}
else if(max2 == null || curr.key.compareTo(max2) > 0)
{
max2 = curr.key;
}
}
return max2;
}
static class Node<E>
{
E key;
Node<E> next;
public Node(E k)
{
key = k;
}
}
static E secondMax(节点头)
{
if(head==null)返回null;
E max2=null;
E max1=head.key;
for(节点curr=head.next;curr!=null;curr=curr.next)
{
如果(当前键比较到(max1)>=0)
{
max2=max1;
max1=当前密钥;
}
else如果(max2==null | | curr.key.compareTo(max2)>0)
{
max2=当前密钥;
}
}
返回max2;
}
静态类节点
{
E键;
节点下一步;
公共节点(ek)
{
key=k;
}
}
当指针
大于Max
时,先前的Max
变为secondMax
,指针
变为新的Max
Max.next
和指针。next
不重要。最后,secondMax
是理想的结果。谢谢你的回复,这就是你所说的max变成secondMax,指针变成新max的意思吗?如果(最大键比较)(指针键)我让你稍微误入歧途了,这有点复杂。如果pointer.key
secondMax.key
和pointer.key
Max.key
,那么secondMax
会变老Max
会变成pointer
;但是如果pointer.key
只会变为secondMax
,secondMax
变为pointer
并且Max
保持不变。使用此代码时,如果(first==null)返回null;如果(size()0&&pointer.key.compareTo(Max.key)>0{secondMax=Max;Max=pointer;}否则如果(pointer.key.compareTo(secondMax.key)>0){secondMax=pointer;}}}返回secondMax.key;}好吧,为了让算法工作,你不能避免从至少secondMax==null
开始,所以你的代码需要准备好处理这个问题。例如,不要只使用if(secondMax.key.compareTo(pointer.key)
static <E extends Comparable<E>> E secondMax(Node<E> head)
{
if(head == null) return null;
E max2 = null;
E max1 = head.key;
for(Node<E> curr=head.next; curr!=null; curr=curr.next)
{
if(curr.key.compareTo(max1) >= 0)
{
max2 = max1;
max1 = curr.key;
}
else if(max2 == null || curr.key.compareTo(max2) > 0)
{
max2 = curr.key;
}
}
return max2;
}
static class Node<E>
{
E key;
Node<E> next;
public Node(E k)
{
key = k;
}
}