标签:
Sort a linked list in O(n log n) time using constant space complexity.
#include<stdio.h> #include<stdlib.h> typedef struct ListNode{ int val; struct ListNode *next; }ListNode; ListNode *mergesort(ListNode *head1, ListNode *head2) { ListNode *q, *p, *tmp, *head; head = (ListNode*)malloc(sizeof(ListNode)); tmp = head; for(p = head1, q = head2; p != NULL && q != NULL; ) { if(p->val > q->val) { tmp->next = q; q = q->next; } else { tmp->next = p; p = p->next; } tmp = tmp->next; } if(p != NULL) tmp->next = p; else if(q != NULL) tmp->next = q; return head->next; } ListNode *sortList1(ListNode *first, ListNode *last) { ListNode *p1, *mid, *midnext; ListNode *head1, *head2; if(first == NULL || first->next == NULL) return first; for(p1 = first, mid = first; p1 != last && p1->next != last; ) { mid = mid->next; p1 = p1->next->next; } midnext = mid->next; mid->next = NULL; //printf("head1:%d, head2:%d\n", first->val, midnext->val); head1 = sortList1(first, mid); head2 = sortList1(midnext, last); return mergesort(head1, head2); } ListNode *sortList(ListNode *head) { ListNode *last = head; if(head == NULL || head->next == NULL) return head; for( ; last->next != NULL; last = last->next) ; //printf("head:%d, last:%d\n", head->val, last->val); return sortList1(head, last); } void main() { ListNode *head, *p1, *p2; int i = 0; p1 = p2 = (ListNode *)malloc(sizeof(ListNode)); scanf("%d", &p1->val); while(p1->val != 0) { i++; if(i == 1) head = p1; else p2->next = p1; p2 = p1; p1 = (ListNode *)malloc(sizeof(ListNode)); scanf("%d", &p1->val); } p2->next = NULL; for(p1 = head; p1 != NULL; p1 = p1->next) printf("%d ", p1->val); printf("\n"); head = sortList(head); for(p1 = head; p1 != NULL; p1 = p1->next) printf("%d ", p1->val); printf("\n"); }
标签:
原文地址:http://blog.csdn.net/uj_mosquito/article/details/42679081