【发布时间】:2014-11-06 07:22:47
【问题描述】:
我已经编写了这段代码来插入和删除元素到链表并形成链表。我想将元素插入到排序列表中的列表中。如何改进我的“添加”方法来做到这一点?
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;
}
【问题讨论】:
-
为了清楚起见,您是在问如何将节点添加到列表的正确排序顺序中?还有你的班级名称是什么?
-
如果您有独特的元素,请使用
SortedSet。它将根据equals()保持正确的顺序。 -
您目前观察到什么问题?
-
我只想按排序顺序插入..这段代码@JasonC没有问题,想要实现删除方法...
标签: java sorting linked-list