partition list

本文介绍了一种链表划分算法,该算法将链表中小于给定值x的所有节点排在大于等于x的节点前面,同时保持原有相对顺序不变。通过示例展示了输入链表1->4->3->2->5->2->null,在x=3的情况下,输出1->2->2->4->3->5->null的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。

你应该保留两部分内链表节点原有的相对顺序。


您在真实的面试中是否遇到过这个题? 
Yes
样例

给定链表 1->4->3->2->5->2->null,并且 x=3

返回 1->2->2->4->3->5->null

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @param x: an integer
     * @return: a ListNode 
     */
    ListNode *partition(ListNode *head, int x) {
        // write your code here
        if(head==NULL||head->next==NULL) return head;
        ListNode *dummy=new ListNode(-1);
        dummy->next=head;
        ListNode *pre=dummy;
        ListNode *cur=head;
        ListNode *firstbigpre=dummy;
        int mark=1;
        while(cur&&cur->val<x){
            cur=cur->next;
            pre=pre->next;
            firstbigpre=firstbigpre->next;
        }
        while(cur){
            if(cur->val<x){
                ListNode *tmp=cur;
                pre->next=cur->next;
                tmp->next=firstbigpre->next;
                firstbigpre->next=tmp;
                firstbigpre=firstbigpre->next;
                cur=pre->next;/////////////////
                }
            else{
                if(mark){firstbigpre=pre;mark=0;}
                pre=pre->next;
                cur=cur->next; 
            }
        }
        return dummy->next;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值