我的这个链表排序思路有问题吗?自测用例通过,但是case一个都没有通过。
单链表的排序
http://www.nowcoder.com/questionTerminal/f23604257af94d939848729b1a5cda08
ListNode* sortInList(ListNode* head){ ListNode* current = head; if(!current||!current->next) return current; else{ int currentValue = current->val; ListNode* nextNode = current->next; int nextValue = nextNode->val; if(currentValue<=nextValue) current->next=sortInList(current->next); else{ ListNode* temp = nextNode->next; current->next = temp; nextNode->next = sortInList(current); current = nextNode; } return current; } }
实现逻辑是:
- 对于只有一个节点的链表直接返回值
- 对于有两个以上节点的,我先取前两个节点Current,NextNode,找到更小的节点,比如Current,此节点的下一个节点就是剩下排序之后的结果(Cuttent->next = sortInList(NextNode)),否则交换节点当前最小元素指向下一个节点为交换后的链表排序结果。