溫馨提示×

php冒泡排序法如何處理鏈表排序

PHP
小樊
81
2024-10-14 02:42:45
欄目: 編程語言

在PHP中,冒泡排序法可以用于對鏈表進行排序。以下是一個使用冒泡排序法對鏈表進行排序的示例:

首先,我們需要創(chuàng)建一個鏈表數據結構。這里我們使用一個簡單的類來表示鏈表的節(jié)點:

class ListNode {
    public $value;
    public $next;

    public function __construct($value) {
        $this->value = $value;
        $this->next = null;
    }
}

接下來,我們實現冒泡排序法對鏈表進行排序的函數:

function bubbleSortLinkedList(ListNode $head): ListNode {
    if ($head === null || $head->next === null) {
        return $head;
    }

    $length = 0;
    $current = $head;
    while ($current !== null) {
        $length++;
        $current = $current->next;
    }

    for ($i = 0; $i < $length - 1; $i++) {
        $current = $head;
        for ($j = 0; $j < $length - 1 - $i; $j++) {
            if ($current->value > $current->next->value) {
                // 交換兩個節(jié)點的值
                $temp = $current->value;
                $current->value = $current->next->value;
                $current->next->value = $temp;
            }
            $current = $current->next;
        }
    }

    return $head;
}

現在,我們可以創(chuàng)建一個鏈表并使用冒泡排序法對其進行排序:

// 創(chuàng)建鏈表 4 -> 2 -> 1 -> 3
$head = new ListNode(4);
$head->next = new ListNode(2);
$head->next->next = new ListNode(1);
$head->next->next->next = new ListNode(3);

// 對鏈表進行排序
$sortedHead = bubbleSortLinkedList($head);

// 打印排序后的鏈表
$current = $sortedHead;
while ($current !== null) {
    echo $current->value . ' -> ';
    $current = $current->next;
}
echo 'null';

輸出結果:

1 -> 2 -> 3 -> 4 -> null

這樣,我們就使用冒泡排序法對鏈表進行了排序。

0