在您的列表中,有一个size字段将有助于存储列表中的元素数量。还要创建类,
SinglyNode implementComparable以便该
compareTo方法表现出所需的效果。实际上,在Single
linkedList中交换两个元素确实很麻烦,而且性能真的很差!
public void bubbleSort{ for (int i = 0; i < size; i++) { for (int j = i; j < size; j++) { if (elementAt(j).compareTo(elementAt(j+1)) > 0) { swap(j, j + 1); } } }}public SinglyNode elementAt(int index){ SinglyNode temp = first; for (int i = 0, i < index; i++) { temp = temp.getNext(); } return temp;}public void swap(int firstIndex, int secondIndex){ SinglyNode secondNext = elementAt(secondIndex).getNext(); SinglyNode second = elementAt(secondIndex); SinglyNode first = elementAt(first); SinglyNode firstPrevious = elementAt(first - 1); firstPrevious.setNext(second); first.setNext(secondNext); second.setNext(first);}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)