Time Limit Exceed?

  • 0
    class Solution {
        ListNode *partition(ListNode *head, int x) {
            ListNode *h = new ListNode(0);
            h -> next = head;
            ListNode *l = new ListNode(0);
            l -> next = NULL;
            ListNode *cur = head, *pre = h, *last = l;
            while (cur != NULL) {
                if (cur -> val < x) {
                    pre -> next = cur;
                    pre = cur;
                } else {
                    last -> next = cur;
                    last = cur;
                cur = cur -> next;
            pre -> next = l -> next;
            return h -> next;

    Totally no idea about why my code exceed the time limit. The input was {2,1}, 2, I tried this input in xcode, it works, and the loop was only executed twice. Is there anyone knows what's wrong with my code? Thanks guys!

  • 4

    I finally figured out why my code exceed the time limit. I didn't write the code to deal with the last node's next pointer, so the pointer points to the head, and the link list become a loop. The time limit exceed happened during the test case. So I couldn't find the reason that my code exceed the time limit.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.