Partition List
来源:互联网 发布:网络维护实训周报 编辑:程序博客网 时间:2024/06/11 07:51
一、问题描述
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
.
二、思路
题目比较有新意,算法导论中有patition算法(非常有名,是快速排序中的核心算法),但是那个算法是基于数组的,这道题目是基于链表的,我的思路是新建两个节点,形成两个链表,将小于x的值放在第一个链表,将大于等于x的值放在第二个链表,循环结束后合并两个链表即可。
三、代码
/** * 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 node1(0),node2(0); ListNode* p1 = &node1, *p2 = &node2; while(head){ if(head -> val < x){ p1 = p1 -> next = head; }else{ p2 = p2 -> next = head; } head = head -> next; } p2 -> next = NULL; p1 -> next = node2.next; return node1.next; }};
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
- [React Native混合开发]React Native for iOS之布局实战(二)
- X264函数功能总结
- Linux 磁盘管理
- 【u004】数列
- [React Native混合开发]React Native for iOS之UI组件
- Partition List
- [React Native混合开发]React Native for iOS之应用
- Jersey采用模板Freemarker输出
- [React Native混合开发]React Native for iOS之动手写组件
- 每日总结0825-Git的安装与使用(一)
- Android逆向之旅---静态方式破解微信获取聊天记录和通讯录信息
- Express 项目中使用 Mongoose
- 【phalcon】完美路由配置 apache nginx
- Mac 配置经常遇到的问题 No Module named xxx