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;
        
        
    }
};
上一篇:扩大缩小Linux物理分区大小


下一篇:【LeetCode】86. 分隔链表