[leetcode] 86. Partition List 解题报告

题目链接:https://leetcode.com/problems/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,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.


思路:悲了催的昨天考驾照permit差点就过了,30题可以错6道,我错了七道得意。不过在美国考驾照只要2刀就行了,只有一个理论和一个路考,感觉比国内应该简单一些。

这题的思路就是创建一个虚拟头结点,然后依次遍历链表碰到比给定数小的就放到前面去,否则就跳过。因为要保持有序,因此我们可以维持一个前面遍历过的比给定数小的链表最后一个结点k,碰到比这个数小的就放到k的后面,这样就保证了链表保持原来的秩序。

代码如下:

/**
 * 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) {
        if(!head) return head;
        ListNode* pHead = new ListNode(0);
        pHead->next = head;
        ListNode* k = pHead, *p = pHead;
        while(p->next)
        {
            ListNode* q = p->next;
            if(q->val < x)
            {
                p->next = q->next;
                q->next = k->next;
                k->next = q;
                k = k->next;
            }
            p = q;
        }
        head = pHead->next;
        delete pHead;
        return head;
    }
};



你可能感兴趣的:(LeetCode,链表)