GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode-1/algorithms/cpp/sortList/sortList.cpp at master · swangcu/leetcode-1 Expand file tree/ Copy pathsortList.cppMore file actions 106 lines (87 loc) · 2.11 KB / Copy pathsortList.cppFile metadata and controls106 lines (87 loc) · 2.11 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 // Source : https://oj.leetcode.com/problems/sort-list/ // Author : Hao Chen // Date : 2014-07-06 /********************************************************************************** * * Sort a linked list in O(n log n) time using constant space complexity. * **********************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <time.h> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *mergeTwoLists(ListNode* head1, ListNode* head2); ListNode *sortList(ListNode *head) { if (head==NULL || head->next == NULL){ return head; } //find the middle place ListNode *p1=head, *p2=head->next; while(p2 && p2->next){ p1 = p1->next; p2 = p2->next->next; } p2 = p1->next; p1->next = NULL; return mergeTwoLists(sortList(head), sortList(p2)); } ListNode *mergeTwoLists(ListNode* head1, ListNode* head2){ ListNode *p1 = head1, *p2=head2; static ListNode dummy(0); ListNode *tail = &dummy; while(p1 && p2){ if(p1->val < p2->val){ tail->next = p1; p1 = p1->next; }else{ tail->next = p2; p2 = p2->next; } tail = tail->next; } if (p1) tail->next = p1; if (p2) tail->next = p2; return dummy.next; } void printList(ListNode* h) { while(h!=NULL){ printf("%d ", h->val); h = h->next; } printf("\n"); } ListNode* createList(int a[], int n) { ListNode *head=NULL, *p=NULL; for(int i=0; i<n; i++){ if (head == NULL){ head = p = new ListNode(a[i]); }else{ p->next = new ListNode(a[i]); p = p->next; } } return head; } int main(int argc, char** argv) { int n = 10; if (argc>1){ n = atoi(argv[1]); } srand(time(NULL)); int *a = new int[n]; for(int i=0; i<n; i++){ a[i] = random()%n + 1; } ListNode *p = createList(a, n); printList(p); printList(sortList(p)); delete[] a; return 0; } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |