LeetCode 86 分隔链表 HERODING的LeetCode之路

给你一个链表和一个特定值 x ,请你对链表进行分隔,使得所有小于 x 的节点都出现在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入:head = 1->4->3->2->5->2, x = 3
输出:1->2->2->4->3->5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:
既然要保留初始相对位置,那么就好操作了,直接定义两个链表,一个小于x的链表,一个大于x的链表,遍历一遍,就可以完成操作,代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* partition(ListNode* head, int x) {
    
    
        // 定义大小两个链表
        ListNode * lowHead = new ListNode(0);
        ListNode * highHead = new ListNode(0);
        ListNode * low = lowHead;
        ListNode * high = highHead;
        while(head != NULL){
    
    
            // 如果小
            if(head -> val < x){
    
    
                low -> next = head;
                low = low -> next;
            }else{
    
    
                // 如果大
                high -> next = head;
                high = high -> next;
            }
            head = head -> next;
        }
        high -> next = NULL;
        // 接上链表
        low -> next = highHead -> next;
        return lowHead -> next;
    }
};


/*作者:heroding
链接:https://leetcode-cn.com/problems/partition-list/solution/guan-fang-ti-jie-xiang-jie-by-heroding-jukz/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/112131396