package LeetCode_LinkedList; /** * 题目: * 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. * Example: * Input: head = 1->4->3->2->5->2, x = 3 * Output: 1->2->2->4->3->5 */ public class Partition_86_1012 { public ListNode Partition(ListNode head,int x ) { if (head == null) { return head; } ListNode head1 = new ListNode(-1); ListNode cur1 = head1; ListNode head2 = new ListNode(-1); ListNode cur2 = head2; ListNode temp = head; while (temp != null) { if (temp.val < x) { cur1.next = temp; cur1 = temp; } else { cur2.next = temp; cur2 = temp; } temp = temp.next; } cur2.next = null; cur1.next = head2.next; return head1.next; } public static void main(String[] args) { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(4); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(2); ListNode node5 = new ListNode(5); ListNode node6 = new ListNode(2); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; node5.next = node6; Partition_86_1012 test = new Partition_86_1012(); ListNode result = test.Partition(node1,3); while (result != null) { System.out.print(result.val + " "); result = result.next; } } }
LeetCode:Partition List(java)
最新推荐文章于 2025-04-21 22:09:55 发布