您的位置:首页 > 其它

leetcode之Insertion Sort List

2013-11-13 21:27 316 查看
Sort a linked list using insertion sort.

此题较简单,就是练习链表增删查问题

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(NULL == head || NULL==head->next) return head;
ListNode *p = head->next, *q, *trace,*pre, *curPre = head;
while(p){
trace = head;
pre = NULL;
q = p->next;
while(trace != p){
//从头节点开始查找节点值是否有比当前节点p值大的
if(trace->val > p->val){
if(NULL == pre){
curPre->next = p->next;
p->next = head;
head = p;
break;
}
curPre->next = p->next;
p->next = pre->next;
pre->next = p;
break;
}

pre = trace;
trace = trace->next;
}
//如果p节点被插入到前面的节点中
if(trace != p){
p = q;
}
else{
curPre = p;
p=p->next;
}
}
return head;

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