Partition List
来源:互联网 发布:明道软件使用 编辑:程序博客网 时间:2024/06/04 18:39
public:
ListNode* partition(ListNode* head, int x) {
if(head==NULL||head->next==NULL) return head;
queue<ListNode*>Q1;
ListNode* p=head,*pre=head,*plast,*pre1;
while(p)
{
if(p->val>=x)
{
Q1.push(p); //找出大于X的值存入队列;
}
p=p->next;
}
while(pre&&pre->val>=x)
{
pre=pre->next; //找出头结点;
}
if(pre==NULL)
{
return head; //全部大于X则返回head;
}
//plast=p;
pre1=pre;
p=pre;
while(p)
{
if(p->val>=x)
{
if(p->next)
{pre1->next=p->next;
p=p->next;}
else pre1->next=NULL,p=p->next; //注意一定要写p=p->next;
}
else
{
pre1=p;
p=p->next;
}
} //为了找出小于X的尾;
plast=pre1; //小于X的尾;
// if(plast==NULL) plast=pre1;
while(!Q1.empty())
{
plast->next=Q1.front();
Q1.pop();
plast=plast->next;
}
plast->next=NULL;
return pre;
}
};
队列一定要判空,循环一定要能否跳出。 null不能再接null,等于号几个一定要看清楚
双队列法
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if(head==NULL||head->next==NULL) return head;
queue<ListNode*>Q1,Q2;
ListNode* p=head,*pre=head,*plast,*pre1;
while(p)
{
if(p->val>=x)
{
Q1.push(p); //找出大于X的值存入队列;
}
else Q2.push(p);
p=p->next;
}
if(Q2.empty())
{
plast=Q1.front();
Q1.pop();
head=plast;
while(!Q1.empty())
{
plast->next=Q1.front();
Q1.pop();
plast= plast->next;
}
plast->next=NULL;
return head;
}
head=Q2.front();
p=head;
Q2.pop();
while(!Q2.empty())
{
p->next=Q2.front();
p=p->next;
Q2.pop();
}
plast=p;
if(plast!=NULL) plast->next=NULL;
if(plast==NULL)
{
plast=Q1.front();
Q1.pop();
head=plast;
}
while(!Q1.empty())
{
plast->next=Q1.front();
Q1.pop();
plast= plast->next;
}
plast->next=NULL;
return head;
}
};
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Php Socket
- grep的常用法
- OC面向对象的三大特征(封装 继承 多态)习题2 复合
- IOS - UITextField输入长度限制
- [Leetcode] Add Two Numbers
- Partition List
- FreeMarker 自定义指令(三)
- 事务机制与锁机制
- 记activity之间的跳转动画
- Launcher3实现壁纸居中
- 写脚本程序的前序工作
- 【mysql】【报错】Mysql外键名重复的错误:duplicate key in table '#sql-*'
- EM及高斯混合模型
- How to install g++-4.6-arm-linux-gnueabihf