牛客网,链表分割(C语言)

链接https://www.nowcoder.com/questionTerminal/0e27e0b064de4eacac178676ef9c9d70
来源:牛客网

编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前 给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
代码:
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        ListNode* cur = pHead;
        ListNode* lessHead,*lessTail,*greaterHead,*greaterTail;
        lessHead = lessTail = (ListNode*)malloc(sizeof(ListNode));
        greaterHead = greaterTail = (ListNode*)malloc(sizeof(ListNode));
        lessTail -> next = NULL;
        greaterTail -> next = NULL;
        while(cur != NULL)
        {
            if(cur->val < x)
            {
                lessTail -> next = cur;
                lessTail = cur;
            }
            else
            {
                greaterTail -> next = cur;
                greaterTail = cur;
            }
            cur = cur ->next;
        }
            lessTail -> next = greaterHead -> next;
            greaterTail ->next = NULL;
            ListNode* list = lessHead ->next;
            free(lessHead);
            free(greaterHead);
            return list;
         
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章