将单向链表按某值划分成左边小、中间相等、右边大的形式(O(1)空间复杂度,稳定划分)
2018-12-23 23:53
686 查看
class Solution { private static ListNode function(ListNode head, int val) { ListNode left = new ListNode(0); ListNode mid = new ListNode(0); ListNode right = new ListNode(0); ListNode tail1 = null, tail2 = null, tail3 = null; ListNode next; ListNode cur = head; while (cur != null) { next = cur.next; if (cur.val < val) { append(left, tail1, cur); tail1 = cur; } else if (cur.val == val) { append(mid, tail2, cur); tail2 = cur; } else { append(right, tail3, cur); tail3 = cur; } cur = next; } return merge(left.next, tail1, mid.next, tail2, right.next, tail3); } private static void print(ListNode head) { while (head != null) { System.out.println(head.val); head = head.next; } } public static void append(ListNode list, ListNode tail, ListNode node) { if (list == null) { return; } if (tail != null) { tail.next = node; } else { list.next = node; } node.next = null; } public static ListNode merge(ListNode l1, ListNode tail1, ListNode l2, ListNode tail2, &nb 5b4 sp; ListNode l3, ListNode tail3) { ListNode head; // find head if (l1 != null) { head = l1; } else if (l2 != null) { head = l2; } else { head = l3; } if (tail1 != null) { tail1.next = l2; } if (tail2 != null) { tail2.next = l3; } else if (tail1 != null) { 2d9a tail1.next = l3; } tail3.next = null; return head; } public static void main(String[] args) { ListNode n1 = new ListNode(9); ListNode n2 = new ListNode(0); ListNode n3 = new ListNode(4); ListNode n4 = new ListNode(5); ListNode n5 = new ListNode(1); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; ListNode head = function(n1, 3); print(head); } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
相关文章推荐
- Java——将单向链表按某值划分成左边小、中间相等、右边大的形式(基础问题)
- 将单向链表按某值划分成左边小、中间相等、右边大的形式
- 将单向链表按某值划分成左边小、 中间相等、 右边大的形式~迎娶是挺
- [链表] - 将单向链表按某值划分成左边小、中间相等、右边大的形式
- 将单向链表按某值划分成左边小、中间相等、右边大的形式
- Java——将单向链表按某值划分成左边小、中间相等、右边大的形式(进阶问题)
- 将单向链表按某个值划分成左边小、中间相等、右边大的形式 Python 版
- 链表问题---将单向链表按某值划分成左边小,中间相等,右边大的形式
- 算法总结之 将单向链表按某值划分成左边小、中间相等、右边大的形式
- 把单链表按某值划分成左边小,中间相等,右边大的形式,时间O(n),空间O(1)
- 将单向链表按某值划分成左边小,中间相等,右边大
- C++将链表划分为左边小,中间等,右边大于pivotKey的形式
- [JS]链表划分给定中间值,小的在左边,大的在右边并保持原排序
- [JS]链表划分给定中间值,小的在左边,大的在右边并保持原排序
- C++链表划分左边小中间等右边大 时间复杂度O(n) 空间复杂度O(1)
- 4.给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。 要求:空间复杂度O(1),时间复杂度为O(n)
- 给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。要求:空间复杂度O(1),时间复杂度为O(n)
- 划分一个整形数组,把负数放在左边,零放在中间,正数放在右边
- 如何重新排列数组使得数组左边为奇数,右边为偶数,并使得空间复杂度为O(1),时间复杂度为O(n)
- 百度笔试:给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。 要求:空间复杂度O(1),时间复杂度为O(n)