Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for ListNode.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode(int val) {
- * this.val = val;
- * this.next = null;
- * }
- * }
- */
- public class Solution {
- /**
- * @param head: The first node of linked list.
- * @param x: an integer
- * @return: a ListNode
- */
- public ListNode partition(ListNode head, int x) {
- // write your code here
- // idea: use two pointer to record smaller partion and larger partion elements separately
- if (head == null) {
- return null;
- }
- ListNode leftDummy = new ListNode(0);
- ListNode left = leftDummy;
- ListNode rightDummy = new ListNode(1);
- ListNode right = rightDummy;
- while (head != null) {
- if (head.val < x) {
- left.next = head;
- left = left.next;
- } else {
- right.next = head;
- right = right.next;
- }
- head = head.next;
- }
- right.next = null;
- left.next = rightDummy.next;
- return leftDummy.next;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement