排序链表【php版】

47 篇文章 1 订阅

在这里插入图片描述

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val = 0, $next = null) {
 *         $this->val = $val;
 *         $this->next = $next;
 *     }
 * }
 */
class Solution {

	/**
	 * 对链表进行排序,使用归并法,无额外空间开销,使用快慢指针法找中点
	 * @param ListNode $head
	 * @return ListNode
	 */
	function sortList($head) {
		if (is_null($head) || is_null($head->next)) {
			return $head;
		}
		return $this->sort($head, null);
	}

	/**
	 * 注:这个链表是包含head, 不包含tail的左闭右开
	 * @param $head
	 * @param $tail
	 */
	function sort($head, $tail) {
		if (is_null($head)) {
			return $head;
		}
		// 这个链表是包含head, 不包含tail的左闭右开
		if ($head->next == $tail) {
			$head->next = null;
			return $head;
		}
		$fast = $head;
		$slow = $head;
		while ($fast != $tail && $fast->next != $tail) {
			$fast = $fast->next->next;
			$slow = $slow->next;
		}
		return $this->mergeTwoList($this->sort($head, $slow), $this->sort($slow, $tail));
	}
	function mergeTwoList($node1, $node2) {
		if (is_null($node1)) {
			return $node2;
		}
		if (is_null($node2)) {
			return $node1;
		}
		$head = null;
		if ($node1->val < $node2->val) {
			$head = $node1;
			$node1->next = $this->mergeTwoList($node1->next, $node2);
		} else {
			$head = $node2;
			$node2->next = $this->mergeTwoList($node1, $node2->next);
		}
		return $head;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
排序链表问题是指对一个链表进行排序。其中,可以使用链表自顶向下归并排序的方法进行排序。具体过程如下: 1. 找到链表的中点,以中点为分界,将链表拆分成两个子链表。可以通过快慢指针的方式来找到链表的中点。快指针每次移动2步,慢指针每次移动1步,当快指针到达链表末尾时,慢指针指向的节点即为链表的中点。 2. 对两个子链表分别进行排序。可以使用递归的方式对子链表进行排序,直到链表为空或者只包含1个节点时,不需要再进行拆分和排序。 3. 将两个排序后的子链表合并,得到完整的排序后的链表。可以使用合并两个有序链表的方法来实现,依次比较两个链表头节点的值,将较小的节点加入到新的链表中。 4. 返回排序后的链表。 以下是Java代码示例: ```java class Solution { public ListNode sortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode slow = head, fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } ListNode tmp = slow.next; slow.next = null; ListNode left = sortList(head); ListNode right = sortList(tmp); ListNode dummy = new ListNode(0); ListNode curr = dummy; while (left != null && right != null) { if (left.val < right.val) { curr.next = left; left = left.next; } else { curr.next = right; right = right.next; } curr = curr.next; } curr.next = left != null ? left : right; return dummy.next; } } ``` 以上是一种解决Java排序链表问题的方法,通过链表自顶向下归并排序的思想,可以对链表进行排序

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值