【Leetcode】【Medium】Partition List
2015-06-18 01:19
330 查看
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
return
解题思路:
1、先条件:输入链表不为空;
2、表头可能改变,因此需要新建一个结点指向表头,或使用二维指针;
3、不变参数:
curNode永远指向待操作结点的前驱(方便删减)
small_end永远指向已经分割的所有小结点中,最后一个结点
big_begin永远指向已经分割的所有大结点中,第一个结点
small_end->next = big_begin;
4、curNode->next为NULL时,循环结束。当发现小结点时,插入small_end和big_begin中间;
代码:
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given
1->4->3->2->5->2and x = 3,
return
1->2->2->4->3->5.
解题思路:
1、先条件:输入链表不为空;
2、表头可能改变,因此需要新建一个结点指向表头,或使用二维指针;
3、不变参数:
curNode永远指向待操作结点的前驱(方便删减)
small_end永远指向已经分割的所有小结点中,最后一个结点
big_begin永远指向已经分割的所有大结点中,第一个结点
small_end->next = big_begin;
4、curNode->next为NULL时,循环结束。当发现小结点时,插入small_end和big_begin中间;
代码:
/** * 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) return head; ListNode* prehead = new ListNode(0); prehead->next = head; ListNode* curNode = prehead; ListNode* small_end = NULL; ListNode* big_begin = NULL; while (curNode->next && curNode->next->val < x) curNode = curNode->next; small_end = curNode; big_begin = small_end->next; while (curNode->next) { if (curNode->next->val < x) { small_end->next = curNode->next; small_end = small_end->next; curNode->next = curNode->next->next; small_end->next = big_begin; } else { curNode = curNode->next; } } head = prehead->next; delete prehead; return head; } };
相关文章推荐
- Java中的泛型(Generic)
- ava web开发 高并发处理
- listview gridview采用setAdapter后如何精确恢复之前的位置
- Samba Server 配置
- Android Studio project消失,project被清空
- AIX网络管理
- mongodb 学习笔记 01 -- 概述,安装,运行
- ok
- [Node.js] Node.js Buffers
- 汇编贪吃蛇
- as3 影片剪辑元件的常用属性
- NotePad++插件——用Customize Toolbar设置自定义小图标按钮
- mac 下终端访问文件出现“Permission Denied”解决方案
- mac 下终端访问文件出现“Permission Denied”解决方案
- NotePad++与MinGw的第一次HelloWorld——C语言环境配置说明
- OPENCV2.2与VS2010配置
- Debian7.5.0安装流程(VirtualBox虚拟机环境)
- XCode7如何使用UI Test
- POJ - 2387 Til the Cows Come Home(最短路Dijkstra模板题)
- 如何使用TestFlight进行Beta测试