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 to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given1->4->3->2->5->2and x = 3,
return1->2->2->4->3->5.

题目的意思比较简单,就是给出一个x,同时给出一个链表。要求是讲链表中的元素重新排序,比x小的数字要排在比x大的数字的前面,同时数字的相对顺序不能变化,如例中的1->4->3->2->5->2,两个2都是在1后面的,所以最后的结果2也在1后面。
这时候我们可以考虑跟归并排序类似的方法(恰好归并排序是稳定算法,题目要求是相对顺序不改变,和稳定性类似),构造重新构造两个链表来存储结点,最后将两个子链表结合并返回头结点即可。代码如下:

/*
struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL){}
};
*/
ListNode *partition(ListNode *head, int x) {
    ListNode *l1 = new ListNode(-1);
    ListNode *l2 = new ListNode(-1);
    ListNode *p = head;
    ListNode *s = l1;
    ListNode *t = l2;
    while (p)
    {
        if (p->val < x)
        {
            s->next = p;
            s = s->next;
        }
        else
        {
            t->next = p;
            t = t->next;
        }
        p = p->next;
    }
    s->next = l2->next;
    t->next = NULL;
    return l1->next;
}

猜你喜欢

转载自blog.csdn.net/h4329201/article/details/78234637