分割链表

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

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

 

示例:

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

思路:

刚开始的思路就是使用两个队列,一个保存小于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) {
        if(!head)
            return NULL;
        queue<ListNode*> small;
        queue<ListNode*> than;
        while(head)
        {
            if(head->val<x)
            {
                small.push(head);
            }
            else{
                than.push(head);
            }
            head = head->next ; 
        }
        ListNode * node;
        ListNode * next;
        if(!small.empty())
        {
            node = small.front();
            small.pop();
            next = node;
        }
        else if(!than.empty())
        {
            node = than.front();
            than.pop();
            next = node;
        }
        while(!small.empty())
        {
            next->next = small.front();
            next = next->next;
            small.pop();
        }
        while(!than.empty())
        {
            next->next = than.front();
            next = next->next;
            than.pop();
        }
        next->next= NULL;
        return node;
    }
};

其实,使用队列来做,无非就是想得到一个大于的,一个小于的,但是使用了存储空间,更优雅一点就是使用双指针,一个连大的,一个连小的,不使用辅助空间。

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(!head) return nullptr;

        ListNode* smaller_head = new ListNode(985); // 定义一个新的链表,用来存比x小的值
        ListNode* smaller = smaller_head; // 定义一个指针,初始位置指在上面的新链表的头结点
        ListNode* larger_head = new ListNode(211); // 定义一个新的链表,用来存比x大或等于x的值
        ListNode* larger = larger_head; // 定义一个指针,初始位置指在上面的新链表的头结点

        while(head)
        {
            if(head -> val < x)
            {
                smaller -> next = head;
                smaller = smaller -> next;
            }
            else
            {
                larger -> next = head;
                larger = larger -> next;
            }
            head = head -> next;
        }

        larger -> next = nullptr;
        smaller -> next = larger_head -> next; // 由此可得,larger_head的头结点,其实是一个dummy值(哑值)

        return smaller_head -> next; // 由此可得,smaller_head的头结点,其实是一个dummy值(哑值)
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值