您的位置:首页 > 其它

leetcode 133: Insertion Sort List

2013-11-19 04:18 411 查看

Insertion Sort List

Total Accepted: 1179
Total Submissions: 4808

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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head==NULL || head->next==NULL) return head;
ListNode *p = head->next;
while(p!=NULL) {
ListNode * q = head;
while(q->val < p->val) {
q=q->next;
}

if(p!=q) {
int temp = q->val;
q->val = p->val;
while(p!=q) {
q = q->next;
swap(temp, q->val);
}
}
p=p->next;
}
return head;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: