Java實現單鏈表的排序
阿新 • • 發佈:2019-01-22
要想實現連結串列的排序,使用雙重迴圈,類似於選擇排序。
外重迴圈從頭結點迴圈到尾節點,內重迴圈從外重迴圈的節點迴圈到尾節點,內重迴圈每個節點的值
與外重迴圈的節點值進行判斷,如果值比外重迴圈的值小,就交換之。
相當與每次迴圈把最小的值放到前面。
下面放上程式碼:
/**
* 連結串列的結構
* @author haoge
*/
public class Node {
//連結串列節點的資料
int data;
//連結串列指向的下一個節點的指標
Node next = null;
public Node(int data) {
this .data = data;
}
}
/**
* 排序連結串列
* @author haoge
*/
public class SortNodeList {
/**
* 對連結串列進行排序:從小到大
* @param head
* @return
*/
public Node sortList(Node head) {
//記錄每次迴圈的最小值
int temp ;
Node curNode = head;
while (curNode != null) {
/**
* 內重迴圈從當前節點的下一個節點迴圈到尾節點,
* 找到和外重迴圈的值比較最小的那個,然後與外重迴圈進行交換
*/
Node nextNode = curNode.next;
while (nextNode != null) {
//比外重迴圈的小值放到前面
if (nextNode.data < curNode.data) {
temp = nextNode.data;
nextNode.data = curNode.data;
curNode.data = temp;
}
nextNode = nextNode.next;
}
curNode = curNode.next;
}
return head;
}
/**
* 新增節點
* @param data
*/
public Node insertNode(int data, Node head) {
Node node = new Node(data);
if (head == null) {
head = node;
return head;
}
Node curNode = head;
//迴圈找到當前連結串列的尾節點
while (curNode.next != null) {
curNode = curNode.next;
}
//尾節點的指標指向新增加的節點
curNode.next = node;
return head;
}
/**
* 列印連結串列
*/
public void printList(Node head) {
Node curNode = head;
//迴圈遍歷到尾節點
while (curNode != null) {
System.out.print(curNode.data + " ");
curNode = curNode.next;
}
System.out.println();
}
public static void main(String[] args) {
SortNodeList sortNode = new SortNodeList();
//連結串列的頭指標
Node head = null;
//新增節點,第一次新增時需要返回頭指標,用於定位連結串列
head = sortNode.insertNode(2, head);
sortNode.insertNode(5, head);
sortNode.insertNode(4, head);
sortNode.insertNode(3, head);
sortNode.insertNode(1, head);
System.out.println("排序連結串列前:");
sortNode.printList(head);
//排序連結串列
head = sortNode.sortList(head);
System.out.println("排序連結串列後:");
sortNode.printList(head);
}
}
輸出結果:
排序連結串列前:
2 5 4 3 1
排序連結串列後:
1 2 3 4 5