leetcode刷刷刷

1.链表节点的插入排序(写了个插入排序,但是报段错误,自己编译器里能运行)

#include <iostream>
#include <stdlib.h>
#include <cstring>
using namespace std;

struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
};

ListNode *insertionSortList(ListNode *head) {
    ListNode *h=new ListNode(0);
    h->next=head;
    ListNode *cur=NULL,*maxptr;
    int max;
    while(h->next!=NULL){ //每次选出最大的一个加入到cur中
        max=-1111111;
        ListNode *p=h;
        while(p->next!=NULL){
            if(p->next->val>max){
                max=p->next->val;
                maxptr=p;
            }
            p=p->next;
        }
        ListNode *tmp=maxptr->next;
        maxptr->next=tmp->next;
        tmp->next=cur;
        cur=tmp;
    }
    delete h;
    h=NULL;
    return cur;
}
    
int main() {
	int i=15,j=2;
	ListNode *p=NULL;
	while(i--){
		ListNode *h=new ListNode(rand()%50);
		h->next=p;
		p=h;
	}
	ListNode *t=p;
	while(t){
		cout<<t->val<<endl;
		t=t->next;
	}
	cout<<endl;
	t=insertionSortList(p); //排序
	while(t){
		cout<<t->val<<endl;
		t=t->next;
	}
	return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/zhang-qc/p/9672148.html