LeetCode 148. 排序链表

匿名 (未验证) 提交于 2019-12-03 00:39:02

使用归并排序的思想

/**  * Definition for singly-linked list.  * struct ListNode {  *     int val;  *     ListNode *next;  *     ListNode(int x) : val(x), next(NULL) {}  * };  */ class Solution {      public:     //使用归并排序     void merge(ListNode* &head, ListNode* &mid, ListNode* &end){ 	if(head==mid && mid==end)             return;          ListNode* p=head, *p1=mid->next;         vector<int> valList;         int K=0;         while(p!=mid->next && p1!=end->next){             if(p->val<=p1->val){                 valList.push_back(p->val);                 K++;                 p=p->next;             }             else{                 valList.push_back(p1->val);                 K++;                 p1=p1->next;             }         }         while(p!=mid->next){             valList.push_back(p->val);             K++;             p=p->next;         }                   while(p1!=end->next){              valList.push_back(p1->val);              K++;              p1=p1->next;         }          ListNode* p2=head;         for(int k=0;k<K;++k){             p2->val=valList[k];             p2=p2->next;         }     }          void mergeSort(ListNode* &head, ListNode* &end){ 	if(head==end) 	    return;          ListNode* pfast=head, *pslow=head;         while(pfast!=end){             if(pfast->next!=end)                 pfast=pfast->next->next; 	    else 		break; 	    pslow=pslow->next;         }                           ListNode* pmid=pslow;//利用快慢指针查找中间节点         if(head!=pmid)             mergeSort(head, pmid);         if(pmid!=end)             mergeSort(pmid->next, end);                  merge(head, pmid, end);     }          ListNode* sortList(ListNode* head) {         if(head==NULL || head->next==NULL)             return head;                  ListNode* end=head; 	while(end->next!=NULL) 	    end=end->next;          mergeSort(head, end);                  return head;     } }; 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!