LeetCode 86.Partition List

题目描述

给定一个链表和一个特定值 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的节点取出来按照顺序组成一个新的链表,遍历完成后将这个新链表放在剩下的链表之前即可。

c++

/**
 * 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 leftHead(-1);
        ListNode rightHead(-1);
        ListNode *currLeft = &leftHead;
        ListNode *currRight = &rightHead;
        for(ListNode *curr = head; curr; curr = curr->next){
            if(curr->val < x){
                currLeft->next = curr;
                currLeft = curr;
            }else{
                currRight->next = curr;
                currRight = curr;
            }
        }
        currLeft->next = rightHead.next;
        currRight->next = nullptr;
        return leftHead.next;
    }
};
发布了61 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/HaoTheAnswer/article/details/104350428