將單向連結串列按某值劃分成左邊小、中間相等、右邊大的形式(O(1)空間複雜度,穩定劃分)
阿新 • • 發佈:2018-12-24
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, 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) { 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; } }