Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

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

思路:

1.由于不能改变原来的相对位置,所以直接置换值是不行的。

2.其实这个题类似于快速排序的Partition函数,该思路是,随机从数组中选取一个值作为参考值,使得数组中比该参考值小的数字排在参考值左端,数组中比该参考值大的数字排在参考值右端。

遍历所有节点,发现比x小的节点就”交换“,交换的过程即先删除那个节点,然后插入到对应位置。

这里有一个前提,即若第一个数就小于x的话,是不需要“交换的”。

另外一点需要注意的是:删除链表某个节点之后,指针p的值可能出现不定义状态,故在删除之前,先让p指向要删除节点的下一个节点。

 class Solution {
public:
//删除链表中位置为loc的节点,从1开始
int Delete(ListNode* &head,int loc){
ListNode* p=NULL;
ListNode* q=NULL;
p=head;
int i=;
//找到前驱节点
while(i<loc-&&p->next){
++i;
p=p->next;
}
q=p->next;
p->next=q->next; int val=q->val;
free(q);
return val;
}
ListNode* Insert(ListNode* &head,int loc,int val){
ListNode* p=head;
p=head;
int i=;
if(loc==){
ListNode* s=(ListNode*)malloc(sizeof(ListNode));
s->val=val;
s->next=p;
return s;
}
//找到前驱节点
while(i<loc-&&p->next){
++i;
p=p->next;
}
ListNode* s=(ListNode*)malloc(sizeof(ListNode));
s->val=val;
s->next=p->next;
p->next=s;
return head;
}
ListNode *partition(ListNode *head, int x) {
if(head==NULL) return NULL;
int insertloc=;
int loc=;
ListNode* p=head;
while(p!=NULL)
{
++loc;
if(p->val<x)
{
++insertloc;
if(insertloc!=loc){
p=p->next;
int val=Delete(head,loc);
head=Insert(head,insertloc,val);
continue;
}
}
p=p->next;
}
return head;
}
};

最新文章

  1. Storm如何保证可靠的消息处理
  2. Sumsets
  3. linux 安装软件程序
  4. ThreadLocal的正确用法
  5. 技术英文单词贴--W
  6. ArcGIS平台中PostgreSQL数据连接配置总结
  7. ./configure:command not found 解决方法
  8. 理解 traits
  9. STM32之触摸屏
  10. ORA-00313错误 及其 解决方法
  11. PHP获取当前文件路径信息的方法
  12. [Swust OJ 794]--最近对问题(分治)
  13. linux 下修改 apache 启动的所属用户和组
  14. 切诺夫界证明(Chernoff bound)
  15. Python3中urllib详细使用方法(header,代理,超时,认证,异常处理) 转
  16. python note 4
  17. jQuery 命名空间的使用
  18. 深入理解 Node.js 中 EventEmitter源码分析(3.0.0版本)
  19. 【PAT】B1076 Wifi密码(15 分)
  20. scu 4439 Vertex Cover

热门文章

  1. 洛谷 P2866 [USACO06NOV]糟糕的一天Bad Hair Day
  2. Java并发编程之原子操作类
  3. docker client和daemom
  4. COM技术开发(一)
  5. Linux配置ssh免密登录
  6. git命令使用(一)
  7. mysql恢复数据
  8. Week06-继承、多态、抽象类与接口
  9. phpstorm的全局操作快捷键ctrl+shift+f被搜狗占用处理方法
  10. vue 运行时 + 编译器 vs. 只包含运行时