(链表)链表的排序问题

  • 题目一:对链表进行排序。
    •   方法一:利用数组进行排序。效率比较低。
      •   代码
        /**
         * Definition for singly-linked list.
         * struct ListNode {
         *     int val;
         *     ListNode *next;
         *     ListNode(int x) : val(x), next(NULL) {}
         * };
         */
        class Solution {
        public:
            ListNode *sortList(ListNode *head) {
                vector<int> res;
                ListNode *temp = head;
                int length = 0;
                while (temp){
                    res.push_back(temp->val);
                    temp = temp->next, length++;
                }
                sort(res.begin(), res.end());
                temp = head;
                int i =0;
                while (temp && i<length){
                    temp->val = res[i];
                    temp = temp->next;
                    i++;
                }
                return head;
            }
        };

         

    •   方法二:对链表进行插入排序
      •   分析:这里其实和插入排序数组类似,但是数组是在原数组的基础上面进行插入排序的,但是对于链表来说比较复杂,所以新建链表进行插入排序。插入排序顾名思义就是一个一个的将数字插入进行,插入的过程中与链表的所有数字进行比较,找到合适的位置进行插入,所以我们设置两个指针,pre指向新链表的头部,cur指向当前链表的当前节点,之后比较两个指针的值,依次插入即可
      •   代码:
        /**
         * Definition for singly-linked list.
         * struct ListNode {
         *     int val;
         *     ListNode *next;
         *     ListNode(int x) : val(x), next(NULL) {}
         * };
         */
        class Solution {
        public:
            ListNode *sortList(ListNode *head) {
                if(head == NULL || head->next == NULL) return head;  
                ListNode* dummyhead = new ListNode(0);  
                ListNode* pre = dummyhead;  
                ListNode* cur = head;  
                  
                while(cur != NULL)  
                {  
                    ListNode* next = cur->next;  //维护链表的下一个结点  
                    pre = dummyhead;             //重置pre为新链表头开始  
                      
                    //在当前排好的新链表中找到第一个大于cur->val的结点  
                    while(pre->next != NULL && pre->next->val <= cur->val)  
                    {  
                        pre = pre->next;  
                    }  
                      
                    //当前pre的next结点的值大于cur的值,将cur插入到pre后  
                    cur->next = pre->next;  
                    pre->next = cur;  
                    cur = next;   //cur指向原链表的下一个节点  
                }  
                return dummyhead->next;  
            }
        };

         

posted @ 2017-02-04 21:11  Kobe10  阅读(771)  评论(0编辑  收藏  举报