温馨提示×

php冒泡排序法如何处理链表排序

PHP
小樊
81
2024-10-14 02:42:45
栏目: 编程语言

在PHP中,冒泡排序法可以用于对链表进行排序。以下是一个使用冒泡排序法对链表进行排序的示例:

首先,我们需要创建一个链表数据结构。这里我们使用一个简单的类来表示链表的节点:

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) {
                // 交换两个节点的值
                $temp = $current->value;
                $current->value = $current->next->value;
                $current->next->value = $temp;
            }
            $current = $current->next;
        }
    }

    return $head;
}

现在,我们可以创建一个链表并使用冒泡排序法对其进行排序:

// 创建链表 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