题意:

image.png

解题思路:

  1. 思路:(线性扫描) O(n)
  2. 1. 定义两个头节点,smallHead, bigHead 分别指向头节点;
  3. 2. 遍历链表,对于小于x的则插入small的后面,反之则插入到big的后面;
  4. 3. 最后将bigHead链表插入到smallHead后面;

PHP代码实现:

  1. /**
  2. * Definition for a singly-linked list.
  3. * class ListNode {
  4. * public $val = 0;
  5. * public $next = null;
  6. * function __construct($val) { $this->val = $val; }
  7. * }
  8. */
  9. class Solution {
  10. /**
  11. * @param ListNode $head
  12. * @param Integer $x
  13. * @return ListNode
  14. */
  15. function partition($head, $x) {
  16. return $this->partition1($head, $x);
  17. $smallHead = new ListNode(0);
  18. $bigHead = new ListNode(0);
  19. $small = $smallHead;
  20. $big = $bigHead;
  21. while ($head) {
  22. $temp = new ListNode($head->val);
  23. if ($head->val < $x) {
  24. $small->next = $temp;
  25. $small = $small->next;
  26. } else {
  27. $big->next = $temp;
  28. $big = $big->next;
  29. }
  30. $head = $head->next;
  31. }
  32. $small->next = $bigHead->next;
  33. return $smallHead->next;
  34. }
  35. // Time: O(n), Space: O(1)
  36. //分割成一大一小两条链表,最后合并
  37. function partition1($head, $x) {
  38. if ($head == null) return;
  39. $smallHead = new ListNode(0);
  40. $bigHead = new ListNode(0);
  41. $small = $smallHead;
  42. $big = $bigHead;
  43. for ($p = $head; $p != null; $p = $p->next) {
  44. if ($p->val < $x) {
  45. $small->next = $p;
  46. $small = $small->next;
  47. } else {
  48. $big->next = $p;
  49. $big = $big->next;
  50. }
  51. }
  52. $small->next = $bigHead->next;
  53. $big->next = null;
  54. return $smallHead->next;
  55. }
  56. }

GO代码实现:

  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. func partition(head *ListNode, x int) *ListNode {
  9. smallHead, bigHead := &ListNode{}, &ListNode{}
  10. small, big := smallHead, bigHead
  11. for head != nil {
  12. temp := &ListNode{head.Val, nil}
  13. if head.Val < x {
  14. small.Next = temp
  15. small = small.Next
  16. } else {
  17. big.Next = temp
  18. big = big.Next
  19. }
  20. head = head.Next
  21. }
  22. big.Next = nil
  23. small.Next = bigHead.Next
  24. return smallHead.Next
  25. }