class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode l1(0),l2(0);
ListNode* l11=&l1,* l22=&l2;
while(head){
ListNode* & a=(head->val>x?l22:l11);
a->next=head;
a=a->next;
head=head->next;
}
l11->next=l2.next;
return l1.next;
}
};
超出时间限制
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode left(0), right(0);
ListNode *l = &left, *r = &right;
while(head){
ListNode* & ref = head->val < x ? l : r;
ref->next = head;
ref = ref->next;
head = head->next;
}
l->next = right.next;
r->next = NULL;
return left.next;
}
};
执行通过 倒数第四行多加了个r->next=NULL 也就是将要提交的链表的最后一个节点指向NULL
https://leetcode.com/problems/partition-list/discuss/29181/10-lines-concise-C++-Solution
@yeze322 高票回答说得很好:强烈不推荐ref这个变量的写法,不要试图在面试/工程代码中加入这些没啥大用的写法。