您的位置:首页 > 其它

list - insertion sort - AC

2014-01-21 12:29 344 查看
/**
 * 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;
        ListNode *cur = head->next;
		ListNode *tmp = NULL;
		while (cur)
		{
			tmp = head;
			while (tmp->val < cur->val && tmp!=cur)
			{
				tmp = tmp->next;
			}
			// 0 0 ;cur = cur->next;
			/*
			tmp->val>=cur->val && tmp == cur; 
			1.1 tmp->val > cur->val && tmp == cur; rediculous ``
			1.2 tmp->val == cur->val && tmp == cur; cur = cur ->next;
			*/
			// 1 0 ;tmp->val < cur->val && tmp == cur; rediculous never happen; cur=cur->next;
			// 0 1 ;insert; the following if is for make the logical covering full
			if (tmp->val >= cur->val && tmp != cur)
			{
				int first = cur->val;
				while (tmp!=cur)
				{
					int second = first;
					first = tmp->val;
					tmp->val = second;

					tmp = tmp->next;
				}

				cur->val = first;
			}
			cur=cur->next;
		}

		return head;
    }
};
be careful of the comment above it can solve the logical full cover problem
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: