ID | Title | Difficulty | |
---|---|---|---|
Loading... |
86. Partition List
Medium
LeetCode
Linked List, Two Pointers
Problem
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
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode dummy1 = new ListNode(0);
ListNode curr1 = dummy1;
ListNode dummy2 = new ListNode(0);
ListNode curr2 = dummy2;
while(head != null){
ListNode temp = new ListNode(head.val);
if(head.val < x){
curr1.next = temp;
curr1 = curr1.next;
} else {
curr2.next = temp;
curr2 = curr2.next;
}
head = head.next;
}
curr1.next = dummy2.next;
return dummy1.next;
}
}
按 <- 键看上一题!
85. Maximal Rectangle
按 -> 键看下一题!
87. Scramble String