Partition List
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
/**
思路:1) 先过一遍,找到Tail节点,然后遇到大的就往后放 缺点是:需要2遍的遍历
2) 维持两个头节点,分别是less_head和greater_head,指向小于x和大于x的链表,原来的List内部的Node只是指针在发生变化。技巧:dummy node的技巧很重要,因为不需要判断head是否为空的问题
教训:1)greater_head指向的链表最后p->next = NULL,否则会导致死循环,这也是刚开始写的时候老是TLE的原因 2)不要用很长的变量名,应该多用ans dp数组 h1 h2 p1 p2这样的变量名,虽然牺牲了一点可读性,但是代码会很简洁,写变量名本身就不会出错了
class Solution { public: ListNode *partition(ListNode *head, int x) { if (!head) return NULL; ListNode * less_head = NULL, *less_p = NULL; ListNode * greater_head = NULL,*greater_p = NULL; for(ListNode * p = head; p; p = p->next){ if (p->val < x){ if (!less_p){ less_head = p; less_p = p; }else{ less_p->next = p; less_p = less_p->next; } }else{ if (!greater_p){ greater_head = p; greater_p = p; }else{ greater_p->next = p; greater_p = greater_p->next; } } } if (less_head){ less_p->next = greater_head; if (greater_p){ greater_p->next = NULL; } return less_head; } return greater_head; } };
上边的代码有很多冗余的地方,不够干净漂亮 1)head是否需要判断 2) 赋值怎么缩减 3)dummy node技巧的使用
class Solution { public: ListNode *partition(ListNode *head, int x) { if (!head) return NULL; //注意这里构造函数next为空,那么应该明确的构造 ListNode h1(0), *p1 = &h1; ListNode h2(0),*p2 = &h2; for(ListNode * p = head; p; p = p->next){ if (p->val < x){ p1 = p1->next = p; }else{ p2 = p2->next = p; } } if (h1.next){ p1->next = h2.next; p2->next = NULL; return h1.next; } return h2.next; } };