Partition List(链表的插入和删除操作,找前驱节点)
2024-08-30 15:52:01
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;
}
};
最新文章
- Storm如何保证可靠的消息处理
- Sumsets
- linux 安装软件程序
- ThreadLocal的正确用法
- 技术英文单词贴--W
- ArcGIS平台中PostgreSQL数据连接配置总结
- ./configure:command not found 解决方法
- 理解 traits
- STM32之触摸屏
- ORA-00313错误 及其 解决方法
- PHP获取当前文件路径信息的方法
- [Swust OJ 794]--最近对问题(分治)
- linux 下修改 apache 启动的所属用户和组
- 切诺夫界证明(Chernoff bound)
- Python3中urllib详细使用方法(header,代理,超时,认证,异常处理) 转
- python note 4
- jQuery 命名空间的使用
- 深入理解 Node.js 中 EventEmitter源码分析(3.0.0版本)
- 【PAT】B1076 Wifi密码(15 分)
- scu 4439 Vertex Cover