[Leetcode] 力扣86:分隔链表

在这里插入图片描述
思路
题目中没有要求在原链表上进行操作,因此可以建立一大一小两个链表。
方法
新建两个链表:small和large。遍历给定链表将节点逐一挂在新建的两个链表上,注意最后对两个链表合并时的处理。

class Solution {
    
    
public:
    ListNode* partition(ListNode* head, int x) {
    
    
        ListNode* small = new ListNode(-1);
        ListNode* large = new ListNode(-1);
        ListNode* smallHead = small;
        ListNode* largeHead = large;
        while (head != nullptr) {
    
    
            if (head -> val < x) {
    
    
                small -> next = head;
                small = small -> next;
            }
            else {
    
    
                large -> next = head;
                large = large -> next;
            }
            head = head -> next;
        }
        large -> next = nullptr;
        small -> next = largeHead -> next;
        return smallHead -> next;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_44537258/article/details/112132287
今日推荐