Beispiel #1
0
 ListNode *sortList(ListNode *head) {
     if(head==NULL||head->next==NULL) return head;
     ListNode *slow=head, *fast=head;
     while(fast->next!=NULL&&fast->next->next!=NULL) {
         fast=fast->next->next;
         slow=slow->next;
     }
     ListNode *tmp=slow->next;
     slow->next=NULL;
     ListNode *l1=sortList(head);
     ListNode *l2=sortList(tmp);
     return mergeSortedList(l1,l2);
 }
Beispiel #2
0
void test_Merge_Sorted_List_function_with_only_single_Element_in_Array()
{
	int arr1[]={2};
  int arr2[]={0};
  int *ptr;

  ptr= mergeSortedList(arr1,arr2,sizeof(arr1)/sizeof(int),sizeof(arr2)/sizeof(int));

  TEST_ASSERT_EQUAL(0,*ptr);
  TEST_ASSERT_EQUAL(2,*(ptr+1));

  free(ptr);
}
Beispiel #3
0
void test_Merge_Sorted_List_function_with_Second_Array_has_more_element()
{
  int arr1[]={2,4,5};
  int arr2[]={0,1,6,20,100};
  int *ptr;

  ptr= mergeSortedList(arr1,arr2,sizeof(arr1)/sizeof(int),sizeof(arr2)/sizeof(int));

  TEST_ASSERT_EQUAL(0,*ptr);
  TEST_ASSERT_EQUAL(1,*(ptr+1));
  TEST_ASSERT_EQUAL(2,*(ptr+2));
  TEST_ASSERT_EQUAL(4,*(ptr+3));
  TEST_ASSERT_EQUAL(5,*(ptr+4));
  TEST_ASSERT_EQUAL(6,*(ptr+5));
  TEST_ASSERT_EQUAL(20,*(ptr+6));
  TEST_ASSERT_EQUAL(100,*(ptr+7));

  free(ptr);
}
//3. 用递归来sort整个list
Node listSort(Node head) {
    Node sorted, l1, l2, item, tem;
    if(head->next == NULL) {
        return head;
    }
    else {
        //分半
        l1 = head;
        tem = findMid(head);
        l2 = tem->next;
        tem->next = NULL;
        //sort每半
        l1 = listSort(l1);
        l2 = listSort(l2);
        //merge两半
        sorted = mergeSortedList(l1,l2);

        return sorted;
    }
}