Skip to content

Instantly share code, notes, and snippets.

@junjiah
Last active January 2, 2016 11:09
Show Gist options
  • Save junjiah/8294838 to your computer and use it in GitHub Desktop.
Save junjiah/8294838 to your computer and use it in GitHub Desktop.
solved 'Insertion Sort List' on LeetCode (1 compile error then AC, not bad :-) http://oj.leetcode.com/problems/insertion-sort-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *insertionSortList(ListNode *head)
{
if (head == NULL) return head;
this->head = head;
while (head->next != NULL)
{
bool proceedOrNot = 1; // ugly, but worked
ListNode *nextAfterInsert = insertion(head->next, proceedOrNot);
if (proceedOrNot)
head = head->next;
else
head->next = nextAfterInsert;
}
return this->head;
}
private:
ListNode *head;
ListNode *insertion(ListNode *curr, bool &proceedOrNot)
{
ListNode *next = curr->next;
if (head->val > curr->val)
{
curr->next = head;
head = curr;
proceedOrNot = 0;
}
else
{
ListNode *iter = head;
while (iter->next != curr)
{
if (iter->next->val >= curr->val)
{
curr->next = iter->next;
iter->next = curr;
proceedOrNot = 0;
break;
}
else
iter = iter->next;
}
}
return next;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment