我已經編寫了此代碼來插入元素並將其移除並形成鏈接列表。我想在排序列表中插入元素到列表中。我怎樣才能改進我的「添加」方法來做到這一點?鏈接列表中的排序列表
public void add(String element)
{
if (isEmpty())
{
first = new Node(element);
last = first;
}
else
{
// Add to end of existing list
last.next = new Node(element);
last = last.next;
}
}
/**
* The toString method computes the string representation of the list.
*
* @return The string form of the list.
*/
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null) {
strBuilder.append("[" + p.value + "]");
p = p.next;
}
return strBuilder.toString();
}
The remove method removes an element.
@param element The element to remove.
@return true if the remove succeeded,
false otherwise.
public boolean remove(String element)
{
if (isEmpty())
return false;
if (element.equals(first.value))
{
// Removal of first item in the list
first = first.next;
if (first == null)
last = null;
return true;
}
// Find the predecessor of the element to remove
Node pred = first;
while (pred.next != null &&
!pred.next.value.equals(element))
{
pred = pred.next;
}
// pred.next == null OR pred.next.value is element
if (pred.next == null)
return false;
// pred.next.value is element
pred.next = pred.next.next;
// Check if pred is now last
if (pred.next == null)
last = pred;
return true;
}
只是爲了清楚起見,你問如何添加一個節點到你的列表的正確排序順序?你的班名是什麼? – 2014-11-06 07:42:15
如果您有獨特的元素,請使用'SortedSet'。它會根據equals()來維護正確的順序。 – Magnilex 2014-11-06 07:59:03
你目前觀察到什麼問題? – 2014-11-06 09:25:23