c++ 链表分割

本文介绍了一种链表分割算法,该算法能够根据给定值x将链表分割为两部分,使得所有小于x的结点排在大于或等于x的结点前面,同时保持原有的数据顺序不变。

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

#include<iostream>
using namespace std;

/**
编写代码,以给定值x为基准将链表分割成两部分,
所有小于x的结点排在大于或等于x的结点之前

给定一个链表的头指针 ListNode* pHead,
请返回重新排列后的链表的头指针。
注意:分割以后保持原来的数据顺序不变。

算法:
涉及到链表的问题一定要使用到指针(指向链表节点的指针)
指针curr small larger分别指向原始链表中的当前节点,
small指向所有小于x的节点构成的子链表的当前节点
larger指向所有大于等于x的节点构成的子链表的当前节点
当curr扫描到当前链表尾部时,将两个子链表和并

关于链表的操作,需要掌握:
根据节点类创建链表(这个过程中隐含着向链表中插入新元素)
以及如何从链表中删除特定元素,

**/

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        // write code here
        if(pHead==NULL){
            return NULL;
        }
        ListNode *curr=pHead;
        ListNode *small=new ListNode(0);
        ListNode *larger=new ListNode(0);
        ListNode *small_head=small;
        ListNode *larger_head=larger;

        while(curr!=NULL){
            if(curr->val<x){
                ListNode* new_node=new ListNode(curr->val);
                small->next=new_node;
                small=small->next;
            }
            else{
                ListNode* new_node=new ListNode(curr->val);
                larger->next=new_node;
                larger=larger->next;
            }
            curr=curr->next;
        }
        if(small_head==small){
            return larger_head->next;
        }
        if(larger_head==larger){
            return small_head->next;
        }
        small->next=larger_head->next;
        return small_head->next;
    }
};

int main(){
    ListNode *pHead=new ListNode(0);
    ListNode *head=pHead;
    int a[3]={6,2,8};
    for(int i=0;i<3;i++){
        ListNode *new_node=new ListNode(a[i]);
        head->next=new_node;
        head=head->next;
    }
    Partition b;
    ListNode *out=b.partition(pHead->next,3);
    while(out!=NULL){
        cout<<out->val<<endl;
        out=out->next;
    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值