leetcode No86. Partition List
来源:互联网 发布:爬虫怎么找兼职 知乎 编辑:程序博客网 时间:2024/06/03 16:52
Question:
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
.
小于x的放前面,大于等于x的放后面
Algorithm:
新建两个链表分别存放小于x的节点和大于等于x的节点。
Accepted Code:
/** * 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* head1=new ListNode(0); //这样不用在while里面判断是否为头节点 ListNode* head2=new ListNode(0); ListNode* l1=head1; ListNode* l2=head2; ListNode* p=head; while(p!=NULL) { if(p->val<x) { l1->next=p; l1=l1->next; } else { l2->next=p; l2=l2->next; } p=p->next; } l2->next=NULL; l1->next=head2->next; return head1->next; }};
0 0
- leetcode No86. Partition List
- 【leetcode每日一题】NO86.Partition List
- LeetCode: Partition List
- LeetCode Partition List
- LeetCode: Partition List
- [Leetcode] Partition List **
- [Leetcode] Partition List
- [LeetCode] Partition List
- leetcode 81: Partition List
- [Leetcode] Partition List
- leetcode 118: Partition List
- [LeetCode]Partition List
- [leetcode]Partition List
- LeetCode-Partition List
- [leetcode] Partition List
- LeetCode - Partition List
- [LeetCode] Partition List
- LeetCode 86: Partition List
- BestCoder Round #86 HDU 5804(暴力),HDU 5805(前缀和后缀差值最大),HDU 5806(尺取法),HDU 5807(简单DAG 分步式DP )
- Android文本的测量和绘制
- UVA 10305 Ordering Tasks(拓扑排序入门)【刘汝佳算法入门经典例6-15】
- Head First 装饰者模式
- 多线程实现的三个方法
- leetcode No86. Partition List
- 安卓端的音乐播放
- hdu2141
- HDU-5806-NanoApe Loves Sequence Ⅱ-DP+队列维护
- 深度学习概述:从感知机到深度网络 (英文版)
- dockerfile-ss
- 抑郁
- Sparse Representation---Yall1---Your algorithms for $L1$
- Service(服务)学习