程序员笔试题----链表的stable_partition

最近腾讯笔试了一道关于链表partition的题,还要求稳定性,当时没有做出来。现在思考了一下,其实不难。只需要根据partition要求分别建立两个链表,然后遍历原链表,调整每个节点的链接即可。时间复杂度为O(n)空间复杂度为O(1)


struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x) :val(x),next(NULL){}
};
void list_partition(ListNode *head, int value){
    if (head == NULL || head->next == NULL) return;
    ListNode *pHead1 = NULL, *pHead2 = NULL, *pNode1 = NULL, *pNode2 = NULL,*node = head;

    for (; node; node = node->next){
        if (node->val < value) { 
            if (pHead1 == NULL){
                pHead1 = node;
                pNode1 = node;
            }
            else{
                pNode1->next = node;
                pNode1 = pNode1->next;
            }
        }
        else{
            if (pHead2 == NULL){
                pHead2 = node;
                pNode2 = node;
            }
            else
            {
                pNode2->next = node;
                pNode2 = pNode2->next;
            }
        }
    }
    if (pNode2)
        pNode2->next = NULL;
    if (pNode1)
        pNode1->next = pHead2;
    return;
}

猜你喜欢

转载自blog.csdn.net/wutao1530663/article/details/67635593