链表分割

 现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。

ListNode* partition(ListNode* pHead, int x) {
        // write code here
        
    ListNode* smallhead = NULL;
    ListNode* smallx = NULL;
    ListNode* bighead = NULL;
    ListNode* bigx = NULL;
    if (pHead == NULL)
        return NULL;
    while (pHead)
    {
        if (pHead->val < x)
        {
            if (smallhead == NULL)
            {
                smallx = pHead;
                smallhead = smallx;
            }
            else
            {
                smallx->next = pHead;
                smallx = smallx->next;
            }
        }
        else  
        {
            if (bighead == NULL)
            {
                bigx = pHead;
                bighead = bigx;
            }
            else
            {
                bigx->next = pHead;
                bigx = bigx->next;
            }
        }
       
        pHead = pHead->next;
    }
    if(bigx)
    bigx->next = NULL;
   
        if (smallhead == NULL)
        {
            return bighead;
        }
        else
        {
            smallx->next = bighead;
            return smallhead;
        }
  
    }
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务