086 Partition List [Leetcode]
2015-08-16 23:16
393 查看
题目内容:
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小的节点依次插入。
注意:可能会存在{2,1},x=2这样的情况,即节点要插入在head之前。为了统一处理,在链表前面加入一个值为INT_MIN的附加头结点。在处理结束后将该节点摘掉。注意指针内存的释放和悬垂指针的处理。
运行时间为8ms,代码如下:
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小的节点依次插入。
注意:可能会存在{2,1},x=2这样的情况,即节点要插入在head之前。为了统一处理,在链表前面加入一个值为INT_MIN的附加头结点。在处理结束后将该节点摘掉。注意指针内存的释放和悬垂指针的处理。
运行时间为8ms,代码如下:
/** * 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; //preHead: additional head ListNode *preHead = new ListNode(INT_MIN); preHead->next = head; head = preHead; //part: the position before the insert node ListNode *part(head); while(part->next != NULL && part->next->val < x) { part = part->next; } if(part->next == NULL) { head = head->next; preHead->next = NULL; delete preHead; preHead = NULL; return head; } //pre: pre-node of p ListNode *p(part->next), *pre(part); while(p != NULL) { if(p->val >= x) { p = p->next; pre = pre->next; } else { pre->next = p->next; p->next = part->next; part->next = p; p = pre->next; part = part->next; } } head = head->next; preHead->next = NULL; delete preHead; preHead = NULL; return head; } };
相关文章推荐
- 【图论专题】8.10~8.12 你见过大蒟蒻写题解吗?点进来你就见过了!
- IPv4地址与整型类型互转_Java_PHP_JavaScript
- 移动开发不同手机弹出数字键盘问题
- c++中几种0值的比较问题
- 数学专题
- pci设备驱动开发以及linux pci设备的重新遍历
- ACM今日学习总结(2015.08.16)
- date、datetime、string的相互转换
- Brainfuck Compiler on PHP
- date、datetime、string的相互转换
- C++对象模型——new 和 delete 运算符(第六章)
- 关于CPU Cache:程序猿需要知道的那些
- 调整jvm内存大小
- 染色 - HYSBZ 2243 树链刨分
- 堆
- string字符串
- ASP.NET(2)——Web服务器对象
- 扩展方法学习总结
- 黑马程序员——枚举(JDK5的新特性)
- python+Eclipse+pydev环境搭建