码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--Insertion Sort List

时间:2015-01-15 16:10:33      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:leetcode   sort   insertsort   linklist   

Sort a linked list using insertion sort.

/**
 * 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 || head->next==NULL)
			return head;
        ListNode* temp = head->next;
		ListNode* pre = head;
		while(temp!=NULL)
		{
			if(temp->val < pre->val)
			{
				head = insert(head,pre,temp);
				temp = pre->next;
			}
			else
			{
			    temp = temp->next;
			    pre = pre->next;
			}
		}
		return head;
		
    }
	ListNode* insert(ListNode* head, ListNode* pre, ListNode* inser)
	{
		ListNode* temp = head;
		ListNode* save = head;
		while(temp->val <= inser->val)
		{
			save = temp;
			temp = temp->next;
		}
		pre->next = inser->next;
		inser->next = temp;
		if(temp == head)
			head = inser;
		else
			save->next = inser;
		return head;
	}
};


LeetCode--Insertion Sort List

标签:leetcode   sort   insertsort   linklist   

原文地址:http://blog.csdn.net/shaya118/article/details/42741003

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!