g0001_0100.s0086_partition_list.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0086_partition_list;
// #Medium #Two_Pointers #Linked_List #2022_02_21_Time_1_ms_(59.29%)_Space_42.2_MB_(29.64%)
import com_github_leetcode.ListNode;
/*
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode nHead = new ListNode(0);
ListNode nTail = new ListNode(0);
ListNode ptr = nTail;
ListNode temp = nHead;
while (head != null) {
ListNode nNext = head.next;
if (head.val < x) {
nHead.next = head;
nHead = nHead.next;
} else {
nTail.next = head;
nTail = nTail.next;
}
head = nNext;
}
nTail.next = null;
nHead.next = ptr.next;
return temp.next;
}
}