Skip to content

Latest commit

 

History

History
55 lines (45 loc) · 1.17 KB

File metadata and controls

55 lines (45 loc) · 1.17 KB

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

解析

将小于x和大于等于x的分成两个链表(less,greater),然后再将 greater 的接在 less 的后面。

代码

/**
 * 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) {
        ListNode less{0};
        ListNode greater{0};
        ListNode* l=&less;
        ListNode* g=&greater;
        ListNode* p=head;
        while(p){
            if(p->val<x){
                l->next=p;
                l=l->next;
            }
            else{
                g->next=p;
                g=g->next;
            }
            p=p->next;
        }
        g->next=nullptr;
        l->next=greater.next;
        return less.next;
        
    }
};