LeetCode | 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 tox.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

思路:

准备两个指针,一个保存小于target的节点,一个保存大于等于target的节点。循环一次完成整个算法。

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode * lt=NULL;
        ListNode * p1=NULL;
        ListNode * gt=NULL;
        ListNode * p2=NULL;
        
        ListNode * p=head;
        while(p != NULL)
        {
            if(p->val < x)
            {
                if(lt == NULL)
                {
                    lt = p;
                    p1 = lt;
                }
                else
                {
                    p1->next = p;
                    p1 = p1->next;
                }
                p = p->next;
                p1->next = NULL;
            }
            else
            {
                if(gt == NULL)
                {
                    gt = p;
                    p2 = gt;
                }
                else
                {
                    p2->next = p;
                    p2 = p2->next;
                }
                p = p->next;
                p2->next = NULL;
            }
        };
        if(p1 == NULL)
        {
            return gt;
        }
        else
        {
            p1->next = gt;
        
            return lt;
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11884927
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞