排序链表
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
这个题逻辑上不算复杂,写起来异常复杂,首先将原表头作为新表头,然后依次取原表里的结点与新表的结点比较,如果小于新表头就头插。大于新表头则遍历新表的结点找到合适的位置插入,特殊情况遍历到表尾也不满足则尾插,然后迭代原表结点。
if(!head || !head->next)//空表或者单结点直接返回原表头 return head; struct ListNode* sorthead=head; struct ListNode* cur=head->next; sorthead->next=NULL; struct ListNode* next=NULL; while(cur) { next=cur->next; if(cur->val<sorthead->val)//头插 { cur->next=sorthead; sorthead=cur; cur=next; } else { struct ListNode* sortcur=sorthead->next; struct ListNode* sortpre=sorthead; while(sortpre) { if(!sortcur)//尾插 { sortpre->next=cur; cur->next=NULL; cur=next; break; } if(cur->val<sortcur->val)//中间插入 { sortpre->next=cur; cur->next=sortcur; cur=next; break; } sortpre=sortcur; sortcur=sortcur->next; } } } return sorthead;
写了半天提交leetcode有个超大的测试用例一直超时真的没办法了,不知道怎么处理
浙公网安备 33010602011771号