[leetcode]Partition List
LeetCode抽风,用Java会runtime error就用c++来写。思路是简单的,写法参考了答案。用了root和pivot两个辅助头结点,就可以免去对是否为NULL的判断。还有要对尾节点的next设为NULL。
class Solution { public: ListNode *partition(ListNode *head, int x) { ListNode* root = new ListNode(-1); ListNode* pivot = new ListNode(-1); ListNode* root_last = root; ListNode* pivot_last = pivot; ListNode* current = head; while (current != NULL) { if (current->val < x) { root_last->next = current; root_last = current; } else { pivot_last->next = current; pivot_last = current; } current = current->next; } root_last->next = pivot->next; pivot_last->next = NULL; return root->next; } };