【LeetCode-链表】分隔链表

题目描述

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:

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

题目链接: https://leetcode-cn.com/problems/partition-list/

思路

x会将链表分割成两部分,左链表中的节点值全都小于x,右链表中的节点值全都大于等于x,则我们可以创建两个链表smallList和bigList,smallList存储左链表,bigList存储右链表。从头开始遍历原链表,当当前节点值小于x时,将当前结点加入smallList;否则加入到bigList。代码如下:

/**
 * 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) {
        if(head==nullptr){
            return nullptr;
        }

        ListNode* smallList = new ListNode(0);  // 数值<x的链表头
        ListNode* bigList = new ListNode(0);    // 数值>=x的链表头
        ListNode* curSmall = smallList;
        ListNode* curBig = bigList;
        ListNode* curNode = head;
        while(curNode!=nullptr){
            if(curNode->val<x){
                curSmall->next = curNode;
                curSmall = curNode;
                curNode = curNode->next;
            }else{
                curBig->next = curNode;
                curBig = curNode;
                curNode = curNode->next;
            }
        }
        curSmall->next = bigList->next;
        curBig->next = nullptr; //  这句别忘了
        return smallList->next;
    }
};
  • 时间复杂度:O(n)
    遍历了链表一遍。
  • 空间复杂度:O(1)
    申请的额外内存不随输入规模的增大而增大。

猜你喜欢

转载自www.cnblogs.com/flix/p/12676093.html