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;
}
};