Partition List
来源:互联网 发布:网络零售的特点与模式 编辑:程序博客网 时间:2024/05/02 01:52
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的串和大于等于x的串。设置4个指针,分别表示这两个串的头尾。注意头指针要用新节点new ListNode(0)而不能用head,否则在第一轮就会把head后的数据丢掉。完成子串的分配后,我们只要把子串头尾相连即可,最后释放掉新建的节点。代码如下:
/** * 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) { if(head==NULL ||head->next==NULL) return head; ListNode *s1=new ListNode(0),*s2=s1,*b1=new ListNode(0),*b2=b1,*tmp=head; while(tmp!=NULL){ if(tmp->val<x){ s2->next=tmp; tmp=tmp->next; s2=s2->next; s2->next=NULL; } else{ b2->next=tmp; tmp=tmp->next; b2=b2->next; b2->next=NULL; } } s2->next=b1->next; head=s1->next; free(s1); free(b1); return head; }};
0 0
- 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
- python第三方库的安装=>LTS
- EditText (编辑文件对象)的各种属性
- MySQL学习笔记:GTID
- org.eclipse.equinox.internal.p2.engine.phases.CheckTrust phase问题
- matlab导出jar包
- Partition List
- 虚拟机vritualBox 下ubuntu14.04设置静态ip地址
- C++补码与原码
- git 撤销操作
- webView 的使用
- hdoj 3183 A Magic Lamp 【RMQ区间取数】
- jEasyUI1.3.6版API中文版(Richie696)
- 蓝懿ios 技术内容交流和学习心得 11.15
- 【Loadrunner】参数化的4种方法