leetcode-148. 排序链表

leetcode-148. 排序链表

题目
leetcode-148. 排序链表

代码

#include <iostream>
using namespace std;

typedef struct ListNode{
	int val;
	ListNode* next;
}ListNode,*ListLink;

void create(ListLink& head){
	int n;
	cin>>n;
	head=new ListNode;
	head->next=NULL;
	ListNode *r=head;
	for(int i=0;i<n;i++){
		ListNode *p=new ListNode;
		cin>>p->val;
		p->next=NULL;
		r->next=p;
		r=p;
	}
}

//快排 
/*ListNode* sortList(ListNode* head) {
	if(!head){
		return head;
	}
	ListNode* dummy = new ListNode;
	dummy->next=head;
	ListNode* last=head;
	ListNode* cur=head->next;
	while(cur){
		if(last->val<=cur->val){
			last=last->next;
		}else{
			ListNode* pre=dummy;
			while(pre->next->val <= cur->val){
				pre=pre->next;
			}
			last->next=cur->next;
			cur->next=pre->next;
			pre->next=cur;
		}
		cur=last->next;
	}
	return dummy->next;
}*/

ListNode* merge(ListNode* head1, ListNode* head2) {
        ListNode* dummyHead = new ListNode;
        dummyHead->next=NULL;
        ListNode* temp = dummyHead, *temp1 = head1, *temp2 = head2;
        while (temp1 != NULL && temp2 != NULL) {
            if (temp1->val <= temp2->val) {
                temp->next = temp1;
                temp1 = temp1->next;
            } else {
                temp->next = temp2;
                temp2 = temp2->next;
            }
            temp = temp->next;
        }
        if (temp1 != NULL) {
            temp->next = temp1;
        } else if (temp2 != NULL) {
            temp->next = temp2;
        }
        return dummyHead->next;
    }
//归并排序 
ListNode* sort(ListNode* head, ListNode* tail) {
    if (head == NULL) {
        return head;
    }
        if (head->next == tail) {
            head->next = NULL;
            return head;
        }
        ListNode* slow = head, *fast = head;
        while (fast != tail) {
            slow = slow->next;
            fast = fast->next;
            if (fast != tail) {
                fast = fast->next;
            }
        }
        ListNode* mid = slow;
        return merge(sort(head, mid), sort(mid, tail));
    }

ListNode* sortList(ListNode* head) {
    return sort(head,NULL);
}

int main(){
	ListNode* head;
	create(head);
	head=sortList(head->next);
	while(head){
		cout<<head->val<<" ";
		head=head->next;
	}
	return 0;
}
上一篇:python测试开发django-148.ECharts 生成环状图(饼图)


下一篇:leetcode-148. 排序链表