Java 排序链表实现

Java 排序链表实现,java,data-structures,linked-list,Java,Data Structures,Linked List,我想在自定义链表中实现排序方法。我试图实现使用冒泡排序,但不知道如何做到这一点 class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } public int getData() { return data; } public void setData(i

我想在自定义链表中实现排序方法。我试图实现使用冒泡排序,但不知道如何做到这一点

class Node {
    int data;
    Node next;

    public Node(int data) {
        this.data = data;
        this.next = null;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}

public class LinkedList {
    private Node head;

    public LinkedList() {
        this.head = null;
    }

    public void insert(int data) {
        Node node = new Node(data);
        if (head == null) {
            head = node;
        } else {
            Node temp = head;

            while (temp.getNext() != null) {
                temp = temp.getNext();
            }
            temp.setNext(node);
        }
    }

    public void reverse() {
        Node temp = head;
        Node back = null;

        while (temp != null) {
            Node next = temp.getNext();
            temp.setNext(back);
            back = temp;
            temp = next;
        }
        head = back;
    }

    public void print() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.getData() + " -- > ");
            temp = temp.getNext();
        }
    }

    public void sort() {
        // Bubble sort (but i am lost)
        Node outer = head;
        while(outer != null){           
            Node inner = head;          
            while(inner != null){   
                // TODO
            }           
            outer = outer.getNext();
        }       
    }
}

您应该从以下伪代码开始:

如果您能够交换第i个和第i个元素,那么您应该能够编写整个内容,因为您知道如何浏览链接列表

procedure bubbleSort( A : list of sortable items )
   n = length(A)
   repeat    
     swapped = false
     for i = 1 to n-1 inclusive do
       /* if this pair is out of order */
       if A[i-1] > A[i] then
         /* swap them and remember something changed */
         swap( A[i-1], A[i] )
         swapped = true
       end if
     end for 
   until not swapped
end procedure