【LeetCode】【86】【Partition List】【链表】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012503241/article/details/82914816

题目: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.
解题思路:
借鉴于:https://leetcode.com/problems/partition-list/discuss/29181/10-lines-concise-C++-Solution
双链表法,left链表代表的是小于x的值的集合,right链表代表的是大于等于x的值的集合。用p和q去连接,注意最后的right = null;
代码:

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
}
    public ListNode partition(ListNode head, int x) {
        if(head == null) return null;
        ListNode left = new ListNode(-1);
        ListNode right = new ListNode(-1);
        ListNode p = left;
        ListNode q = right;
        while (head!=null){
            if(head.val<x){
                p.next = head;
                p = p.next;
            }else {
                q.next = head;
                q = q.next;
            }
            head = head.next;
        }
        p.next = right.next;
        q.next = null;
        return left.next;
    }

猜你喜欢

转载自blog.csdn.net/u012503241/article/details/82914816