【发布时间】:2012-12-25 14:22:25
【问题描述】:
我有一个需要排序的LinkedList(它包含ints),我不知道该怎么做。谁能给我的源代码来排序一个 int 链表?
我尝试了这个我在网上找到的代码,但它不起作用。
public void sort(LinkedList sortlist)
{
//Enter loop only if there are elements in list
boolean swapped = (head != null);
// Only continue loop if a swap is made
while (swapped)
{
swapped = false;
// Maintain pointers
Node curr = head;
Node next = curr.link;
Node prev = null;
// Cannot swap last element with its next
while (next != null)
{
// swap if items in wrong order
if (curr.data>next.data)
{
// notify loop to do one more pass
swapped = true;
// swap elements (swapping head in special case
if (curr == head)
{
head = next;
Node temp = next.link;
next.link = curr;
curr.link = temp;
curr = head;
}
else
{
prev.link = curr.link;
curr.link = next.link;
next.link = curr;
curr = next;
}
}
// move to next element
prev = curr;
curr = curr.link;
next = curr.link;
}
}
}
【问题讨论】:
标签: algorithm sorting data-structures linked-list