LeetCode 86. Partition List

题目

操作指针的题目

/**
 * 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==NULL)
            return head;
        if(head->next==NULL)
            return head;
        ListNode *term = head;
        
        ListNode *head2 = new ListNode(-1);
        ListNode *head3 = head2;
        
        int tag=0;
        
        ListNode *pre = head;
        
        while(term!=NULL)
        {
            if(term->val < x)
            {
                head2->next = term;
                head2 = head2->next;
                
                if(tag==0)
                {
                    head = term->next;
                    pre = head;
                }
                else
                {
                    pre->next = term->next;
                }
            }
            else
            {
                tag=1;
                pre = term;
            }
            
            term = term->next;
        }
        
        head2->next = head;
        
        head = head3->next;
        
        return head;
        
        
    }
};
posted @ 2019-12-02 14:44  Shendu.CC  阅读(104)  评论(0编辑  收藏  举报