我在我的情況下有一個雙向鏈表。我想找到最大和最小元素。所以我想用集合來找到它。這裏是我下面的代碼節點首先:如何找到鏈接列表的最大/最小元素
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