leetcode 刷题之路 82 Partition List
来源:互联网 发布:黑色沙漠台服捏脸数据 编辑:程序博客网 时间:2024/06/05 00:13
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
.
将链表中值小于某个数的节点移动到前半部分,/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *partition(ListNode *head, int x)
{
ListNode* dummyHead1=new ListNode(0);
ListNode* dummyHead2=new ListNode(0);
ListNode *p=dummyHead1,*q=dummyHead2;
while(head!=NULL)
{
if(head->val<x)
{
p->next=head;
head=head->next;
p=p->next;
}
else
{
q->next=head;
head=head->next;
q=q->next;
}
}
p->next=NULL;
q->next=NULL;
p->next=dummyHead2->next;
p=dummyHead1->next;
delete dummyHead1;
delete dummyHead2;
return p;
}
划分链表,使得值小于某个数的节点都位于链表的前半部分,大于等于这个数的节点位于链表后半部分,且每部分的节点相对顺序保持不变。
方便起见,使用两个辅助头结点dummyHead1,dummyHead2作为两个链表的头结点,分别存储值小于给定数据的节点和值大于等于给定数据的节点,遍历原链表,根据链表节点值大小比较结果将节点移动到这两个辅助头结点表示的某一个链表中,最后再将两个链表头尾相连拼接即可。
代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *partition(ListNode *head, int x) { ListNode* dummyHead1=new ListNode(0); ListNode* dummyHead2=new ListNode(0); ListNode *p=dummyHead1,*q=dummyHead2; while(head!=NULL) { if(head->val<x) { p->next=head; head=head->next; p=p->next; } else { q->next=head; head=head->next; q=q->next; } } p->next=NULL; q->next=NULL; p->next=dummyHead2->next; p=dummyHead1->next; delete dummyHead1; delete dummyHead2; return p; }};
- leetcode 刷题之路 82 Partition List
- LeetCode 之 Partition List
- LeetCode之Partition List
- leetcode之Partition List
- LeetCode之Partition List
- leetcode之Partition List
- leetcode之Partition List
- Leetcode之partition-list
- leetcode:单链表之Partition List
- Leetcode之Partition List 问题
- [leetcode刷题系列]Partition List
- LeetCode刷题笔录Partition List
- LeetCode 之 Partition List — C++ 实现
- [LeetCode刷题记录]Partition List
- 开始刷leetcode day15:Partition List
- 【leetcode每日一题】NO86.Partition List
- LeetCode: Partition List
- LeetCode Partition List
- [MySQL FAQ]系列 — 如何安全地关闭MySQL实例
- JAVA设计模式之单例模式
- 第一次用GitHub教程(第一次用GitHub新得心得)
- 骨牌铺方格
- 数据挖掘笔记-特征选择-遗传算法
- leetcode 刷题之路 82 Partition List
- Android开发工具类大集合(六)
- 解决 JBOSS5.1下 不识别 Struts2注解
- C与C++的区别与联系
- 被微软拒的第一天 - 我要踏实!
- 004
- hdoj 3652 数位dp
- POJ - 2478 Farey Sequence
- Servlet编程实现实现图形验证码