Partition List

描述

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.

分析

代码

  1. // Partition List
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public ListNode partition(ListNode head, int x) {
  5. ListNode left_dummy = new ListNode(-1); // 头结点
  6. ListNode right_dummy = new ListNode(-1); // 头结点
  7. ListNode left_cur = left_dummy;
  8. ListNode right_cur = right_dummy;
  9. for (ListNode cur = head; cur != null; cur = cur.next) {
  10. if (cur.val < x) {
  11. left_cur.next = cur;
  12. left_cur = cur;
  13. } else {
  14. right_cur.next = cur;
  15. right_cur = cur;
  16. }
  17. }
  18. left_cur.next = right_dummy.next;
  19. right_cur.next = null;
  20. return left_dummy.next;
  21. }
  22. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/linked-list/partition-list.html