Created
October 8, 2023 10:16
-
-
Save alvinlau/d895a54841248dd9acd752c16e022d9b to your computer and use it in GitHub Desktop.
86. Partition List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # https://leetcode.com/problems/partition-list/ | |
| # 86. Partition List | |
| # Given the head of 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 1: | |
| # Input: head = [1,4,3,2,5,2], x = 3 | |
| # Output: [1,2,2,4,3,5] | |
| # Example 2: | |
| # Input: head = [2,1], x = 2 | |
| # Output: [1,2] | |
| # Constraints: | |
| # The number of nodes in the list is in the range [0, 200]. | |
| # -100 <= Node.val <= 100 | |
| # -200 <= x <= 200 | |
| # Definition for singly-linked list. | |
| # class ListNode | |
| # attr_accessor :val, :next | |
| # def initialize(val = 0, _next = nil) | |
| # @val = val | |
| # @next = _next | |
| # end | |
| # end | |
| # @param {ListNode} head | |
| # @param {Integer} x | |
| # @return {ListNode} | |
| def partition(head, x) | |
| return head unless head && head.next | |
| # just build two lists represented by head1|2 and tail1|2 | |
| cur = head | |
| head1 = head2 = tail1 = tail2 = nil | |
| while cur | |
| if cur.val < x | |
| if head1 | |
| tail1.next = cur | |
| tail1 = cur | |
| else | |
| head1 = tail1 = cur | |
| end | |
| else | |
| if head2 | |
| tail2.next = cur | |
| tail2 = cur | |
| else | |
| head2 = tail2 = cur | |
| end | |
| end | |
| cur = cur.next | |
| end | |
| return head2 unless head1 # in case no list1 | |
| tail1.next = head2 | |
| tail2.next = nil if tail2 # in case no list2 | |
| head1 | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment