Partition List
来源:互联网 发布:淘宝管制刀具 编辑:程序博客网 时间:2024/06/06 10:06
Description:
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的放到后面,每部分元素的原始相对位置不变。
思路:遍历一遍链表,把小于x的都挂到head1后,把大于等于x的都放到head2后,最后再把大于等于的链表挂到小于链表的后面就可以了。
#include <iostream>using namespace std;class LNode{public: int val; LNode *next; LNode(int x):val(x),next(nullptr){ }};class Solution{public: LNode* partitionList(LNode* L,int x) { LNode left_head(-1) ; //头节点 LNode right_head(-1) ; //头节点 auto left = &left_head; auto right = &right_head; LNode *cur = L->next; //用来遍历链表的 while (cur != nullptr) { if (cur->val < x) { left->next = cur; left = cur; } else { right->next = cur; right = cur; } cur = cur->next; } left->next = right_head.next; //连接起来 right->next = nullptr; return left_head.next; }};int main(){ LNode *L = new LNode(-1); //创建头节点 LNode *p = L; int value; //尾插法创建一个链表,输入1->4->3->2->5->2 for (int i = 0; i < 6 ; ++i) { cin>>value; p->next = new LNode(value); p = p->next; cout<<p->val; if (i < 5) cout<<"->"; } cout<<endl; int x = 3; Solution solution; LNode *q = solution.partitionList(L,x); LNode *ptr; //输出链表 while (q != nullptr) { ptr = q; cout<<q->val; if (q->next != nullptr) cout<<"->"; q = q->next; delete ptr;//释放分配的内存 } cout<<endl; return 0;}
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
- JdbcTemplate 使用了模版模式和回调函数:
- iOS改变Navigationbar透明度
- PHP 命名空间(namespace)
- OS X文本编辑器引号自动变化的问题
- iOS第三方框架集合
- Partition List
- C语言指针导学(4)——分清函数指针和指针函数
- docker 使用笔记
- 传奇生物-龙
- 笔试经验之318
- 正则表达式
- 2015年度小结
- 圣人不法古,不修今。法古则后于时,修今则塞于势。
- android 退出应用优雅的方式(新加一种)