您的位置:首页 > 其它

LeetCode Insertion Sort List

2014-07-15 10:20 429 查看
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) {
ListNode *pNode = head;
if (head == NULL || head->next == NULL)
return head;
while (pNode->next != NULL) {
ListNode *ptemp = pNode->next;
pNode->next = ptemp->next;

ListNode *ps = head;
ListNode *pbehind = head;
while (ps != pNode->next) {
if (ps->val < ptemp->val) {
pbehind = ps;
ps = ps->next;
} else
break;
}

if (ps == head) {
ptemp->next = ps;;
head = ptemp;
}
else if (pbehind == pNode) {
ptemp->next = ps;
pbehind->next = ptemp;
pNode = pNode->next;
}
else {
ptemp->next = ps;
pbehind->next = ptemp;
}
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode