LinkedList - 86. Partition List

58

86. Partition List

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

思路:

题目意思是给一个链表和一个数字,将链表前半部分变成小于这个数字后半部大于等于这个数字。考的是链表基本操作。使用两个指针,记录下比输入小的链表和大于等于该数字的链表,再把两个链表接起来。

代码:

java:

/**

 * 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 l1 = new ListNode(0), l2 = new ListNode(0);
        ListNode p1 = l1, p2 = l2;
        
        while (head != null){
            if (head.val < x) {
                p1 = p1.next = head;
            } else {
                p2 = p2.next = head;
            }
            head = head.next;
        }
        
        p1.next = l2.next;
        p2.next = null;
        
        return l1.next;
    }
}