Loading

partition-list

题意略:

说一下自己的两个坑点:当为空表或者只有一个节点时,应该返回head而不是NULL

#include<iostream>
using namespace std;
 struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        if (head == NULL||head->next==NULL)return head;
        ListNode *head1 = new ListNode(-1);
        ListNode *head2 = new ListNode(-1);
        ListNode *end1 = head1;
        ListNode *end2 = head2;
        ListNode *p = head;
        while (p){
            if (p->val < x){
                end1 = end1->next = p;
            }
            else{
                end2 = end2->next = p;
            }
            p = p->next;
        }
        end2->next = NULL;
        end1->next = head2->next;
        return head1->next;
    }
};

 

posted @ 2018-11-21 14:07  青山新雨  阅读(281)  评论(0编辑  收藏  举报