CM11 链表分割
- 描述
 - 示例
 - 解题思路以及代码
 - 解法1
 - 解法2
 
描述
现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。
示例

 
解题思路以及代码
解法1
申请两个头结点,小的放在minhead,大的放在maxhead,再把两个链表连接起来。
 
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        // write code here
        struct ListNode* minhead=(struct ListNode*)malloc(sizeof(struct ListNode));
        struct ListNode* maxhead=(struct ListNode*)malloc(sizeof(struct ListNode));
        struct ListNode* mintail=minhead;
        struct ListNode* maxtail=maxhead;
        struct ListNode* cur=pHead,*next=NULL;
        while(cur)
        {
            next=cur->next;
            if(cur->val < x)
            {
                mintail->next=cur;
                mintail=mintail->next;
            }
            else
            {
                maxtail->next=cur;
                maxtail=maxtail->next;
            }
            cur=next;
        }
        mintail->next=maxhead->next;
        maxtail->next=NULL;
        struct ListNode* head=minhead->next;
        free(minhead);
        free(maxhead);
        return head;
    }
};
 
解法2
不申请头结点,小的放在minhead,大的放在maxhead,然后链接起来,这种做法要注意,minhead和maxhea链表为空的情况,要做近一步处理
 
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        // write code here
        struct ListNode* minhead,*mintail;
        struct ListNode* maxhead,*maxtail;
        minhead=mintail=NULL;
        maxhead=maxtail=NULL;
        struct ListNode* cur=pHead,*next=NULL;
        while(cur)
        {
            next=cur->next;
            if(cur->val < x)
            {
                if(mintail == NULL)
                {
                    minhead=mintail=cur;
                }
                else 
                {
                    mintail->next=cur;
                    mintail=mintail->next;
                }
            }
            else
            {
                if(maxtail == NULL)
                {
                    maxhead=maxtail=cur;
                }
                else 
                {
                    maxtail->next=cur;
                    maxtail=maxtail->next;
                }
            }
            cur=next;
        }
        //maxhead或minhead链表为空
        if (maxtail == NULL)
        {
            return minhead;
        }
        else if (mintail == NULL)
        {
            return maxhead;
        }
        else
        {
            mintail->next = maxhead;
            maxtail->next = NULL;
            return minhead;
        }
        
    }
};
                

















