链表插入排序

来源:互联网 发布:spss数据描述统计分析 编辑:程序博客网 时间:2024/06/07 15:29

描述

用插入排序对链表排序

样例

Given 1->3->2->0->null, return 0->1->2->3->null

思考

  1. 非插入排序
  2. 插入排序

代码

//  By Lentitude/** * Definition of ListNode * class ListNode { * public: *     int val; *     ListNode *next; *     ListNode(int val) { *         this->val = val; *         this->next = NULL; *     } * } */class Solution {public:    /**     * @param head: The first node of linked list.     * @return: The head of linked list.     */    ListNode *insertionSortList(ListNode *head) {        // write your code here        /**         * 先计算节点的总数         * 进行遍         */         ListNode *temp = head, *l1;         int numOfList = 0; // 节点数目         while (temp){             ++numOfList;             temp = temp->next;         }         for (int i = 0; i != numOfList; ++i){             for (l1 = head; l1->next != NULL; l1 = l1->next){                 if(l1->val > l1->next->val ){                     swap(l1->val, l1->next->val);                 }             }         }         return head;    }};

//  By Lentitude
0 0
原创粉丝点击