LeetCode86 Partition List

题目链接:

https://leetcode.com/problems/partition-list/

题目描述:

将一个链表重排,比x小的节点在大于或等于x的节点前面。不改变之前的相对顺序,只是把比x小的节点,按之前相对先后顺序,放在前面。

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

分析:

一些小问题还是调了有好久。加了一个头指针的节点pHead,方便在head之前插入节点。

代码:
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode* pHead=(ListNode*)malloc(sizeof(ListNode));
        pHead->next=head;
        ListNode* less=pHead;
        ListNode* pre=pHead;
        ListNode* cur=head;
        while(cur!=NULL){
            if(cur->val<x){
                if(pre==less){ //当pre与less保持同步时,表明还没有发现比x大的节点
                    less=cur;
                    pre=cur;
                    cur=cur->next;
                }
                else{
                    ListNode* tmpLess=less->next;
                    pre->next=cur->next;
                    less->next=cur;
                    cur->next=tmpLess;
                    less=cur;
                    cur=pre->next;
                }
            }
            else{
                pre=cur;
                cur=cur->next;
            }
        }
        return pHead->next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值