LeetCode(148) Sort List

来源:互联网 发布:stm32用ucos还是linux 编辑:程序博客网 时间:2024/04/26 19:34

当程序出现出错后,一个可行的方法是逐行检查。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *findMid(ListNode *head) {        if(head == NULL)            return NULL;        ListNode *fast = head;        ListNode *slow = head;        while(fast->next != NULL) {            fast = fast->next;            if(fast->next != NULL) fast = fast->next;            slow = slow->next;        }        return slow;    }    ListNode* sortList(ListNode* head) {        if(head == NULL)            return NULL;        if(head->next == NULL)            return head;        ListNode *mid = findMid(head);        ListNode *midPre;        ListNode *p1 = head;        while(p1->next != mid)            p1 = p1->next;        midPre = p1;        midPre->next = NULL;        ListNode *leftList = sortList(head);        ListNode *rightList = sortList(mid);        return mergeTwoLists(leftList, rightList);    }    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {          ListNode *p1,*p2,*p3;          p1 = l1;          p2 = l2;          ListNode *l3 = new ListNode(0);          p3 = l3;          while(p1 != NULL || p2 != NULL) {              if(NULL == p1) {                  p3->next = p2;                  p3 = p3->next;                  p2 = p2->next;                  continue;              }              if(NULL == p2) {                  p3->next = p1;                  p3 = p3->next;                  p1 = p1->next;                  continue;              }              if(p1->val <= p2->val) {                  p3->next = p1;                  p3 = p3->next;                  p1 = p1->next;              }else {                  p3->next = p2;                  p3 = p3->next;                  p2 = p2->next;              }          }          return l3->next;      }  };
0 0
原创粉丝点击