我在我的情况下有一个双向链表。我想找到最大和最小元素。所以我想用集合来找到它。这里是我下面的代码节点首先:如何找到链接列表的最大/最小元素
public class Node<T> {
Node<T> prev;
Node<T> next;
T data;
public Node(T _data)
{
data = _data;
prev = null;
next = null;
}
public Node(T _data, Node<T> _prev, Node<T> _next)
{
data = _data;
prev = _prev;
next = _next;
}
T getData()
{
return data;
}
public void setNext(Node<T> _next)
{
next = _next;
}
public void setPrev(Node<T> _prev)
{
prev = _prev;
}
public Node<T> getNext()
{
return next;
}
public Node<T> getPrev()
{
return prev;
}
}
,这里是我的双向链表类:
public class DoublyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
int listCount = 0;
public void traverseF()
{
Node<T> temp = head;
while(temp != null)
{
System.out.print(temp.getData() + " ");
temp = temp.getNext();
}
}
public void traverseB()
{
Node<T> temp = tail;
while(temp != null)
{
System.out.print(temp.getData() + " ");
temp = temp.getPrev();
}
}
public void insertFirst(T data)
{
Node<T> temp = new Node<T>(data);
if(head == null)
{
head = temp;
tail = temp;
temp.setNext(null);
temp.setPrev(null);
}
else
{
temp.setNext(head);
head.setPrev(temp);
head = temp;
}
}
}
所以,我的主要代码:
import java.util.Collections;
public class glavna {
public static void main(String[] args) {
DoublyLinkedList<Integer> DLL = new DoublyLinkedList<Integer>();
DLL.insertFirst(32);
DLL.insertFirst(22);
DLL.insertFirst(55);
DLL.insertFirst(10);
DLL.traverseF();
Integer max = Collections.max(DLL);
}
}
究竟是如何做的我调用Collections.max或Collections.min方法?是不是只有找到最大/最小元素的列表?
public T getMin()
{
Node<T> temp = head;
T min = head.getData();
while(temp.getNext() != null)
{
if(temp.getData() < min) // error
{
//min = temp.getData();
}
}
}
您的'DoublyLinkedList'应该实现'Collection'接口,即''public class DoublyLinkedList implements Collection''。然后你可以调用'Collections.max(DLL)' – kiruwka 2014-11-08 21:05:17
实现Collection接口的另一种方法是在'insertFirst()'方法中跟踪当前的最小值和最大值。然后,创建一个'getMin()'和'getMax()'方法来返回O(1)中的最小值和最大值。 – 2014-11-08 21:10:27
@kiruwka'收藏'界面究竟是什么?有什么例子可以实现吗?谢谢。 – user12831231 2014-11-08 21:10:46