lintcode: Partition List
来源:互联网 发布:mac怎么玩英雄联盟 编辑:程序博客网 时间:2024/06/09 14:43
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->null and x = 3, return
1->2->2->4->3->5->null.
这题思路貌似很简单。
1.开个两个空间,分别作为小于x和大于等于x的头结点(不放数据)head1,head2。
2.但是就这么简单的程序我却错了好几次,原因:
(1)p1->next=NULL;
没有对新链的末尾next指针赋为NULL,这样链不知道什么时候截止;
(2)p1->next=NULL;
后发现程序还是出错。发现了原因,原来,修改了p1->next也就相当于修改为了p,p修改了p的next就丢失了,所以事先要记录next。
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */class Solution {public: /** * @param head: The first node of linked list. * @param x: an integer * @return: a ListNode */ ListNode *partition(ListNode *head, int x) { // write your code here if(head==NULL){ return NULL; } ListNode *head1=new ListNode(0); ListNode *p1=head1; ListNode *head2=new ListNode(0); ListNode *p2=head2; ListNode* p=head; while(p){ ListNode* next=p->next;//!! if(p->val<x){ p1->next=p; p1=p1->next; p1->next=NULL;//!! }else{ p2->next=p; p2=p2->next; p2->next=NULL;//!! } p=next; } p1->next=head2->next; return head1->next; }};
0 0
- [Lintcode]Partition List
- lintcode: Partition List
- LintCode Partition List 链表划分
- lintcode:Partition Array
- lintcode:Partition Array
- LintCode Partition Array
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- const的用法(用在函数前面与后面的区别)
- 一行Shell代码查找所有代码行数
- 可伸缩性, 可用性和稳定性模式 Scalability, Availability & Stability Patterns
- android Animation 动画
- pitch yaw roll是什么
- lintcode: Partition List
- 自定义Dialog实现全屏和位置在屏幕底部
- Easyui中使用jquery或js动态添加元素时出现的样式失效的解决方法
- HTML5通信API
- Mybatis入门(三):增删改查
- git的使用
- Mac下安装Tomcat
- Windows下PHP线程安全与非线程安全、Apache版本选择,及详解五种运行模式。
- [LeetCode]96. Unique Binary Search Trees