曾經遇到的一個面試題,快速排序用鏈表實現,算法和以前的相似,需要注意一些細節處理

typedef struct nodes{
	int data;
	struct nodes * next;
} node;

void add_node(node *first,int data)
{
	node * tmp;
	if (first != NULL){
		tmp =(node *) malloc(sizeof(node));
		if (tmp != NULL) {
			tmp->data= data;
			tmp->next = NULL;		
		}
		while ( first-> next != NULL)
			first = first->next;
		first->next = tmp;
	}
		
}

void print_link(node * first)
{
	while (first){
		printf("%d ",first->data);
		first=first->next;
	}
	printf("\n");
}

node * partion_list(node *first, node * end, node * & ret_little )
{
	node *little=NULL,*big=NULL,*tmp=NULL;

	tmp = first;
	first = first->next;
	tmp->next = NULL;
	while (first != end) {
		if (tmp->data > first->data) {
			if (little == NULL) {
				little = first;
				first = first->next;
				little->next = NULL;
			} else {
				node * t = little;
				while ( t->next != NULL ) t = t->next;
				t->next = first;
				first = first->next;
				t->next->next=NULL;
			}
		} else {
			if (big == NULL) {
				big = first;
				first = first->next;
				big->next = NULL;
			} else {
				node * t = big;
				while ( t->next != NULL ) t = t->next;
				t->next = first;
				first = first->next;
				t->next->next=NULL;
			}
		}
	}
	node *t =little;
	while ( t != NULL && t->next != NULL ) t = t->next;
	if (little != NULL) {
		t->next=tmp;
		ret_little = little;
	} else {
		ret_little = tmp;
	}
	tmp->next = big;
	return tmp;
}

node * quick_list(node *first, node *end)
{
	if ( first == NULL || first == end)  return first;
	node * new_first=NULL;
	node * tmp = partion_list(first,end,new_first);
	print_link(new_first);
	node * p = new_first;

	if (new_first == tmp && tmp ->next == NULL) {
		printf("1\n");
		return tmp;
	} else if (new_first == tmp) {
		printf("2\n");
		node * end = quick_list(tmp->next,NULL);
		tmp->next = end;
		return tmp;
	} else if (tmp ->next == NULL) {
		printf("3\n");
		p = new_first;
		while (p->next != tmp) p = p->next;
		p->next = NULL;
		node * start = quick_list(new_first,NULL);
		p = start;
		while ( p->next != NULL) p = p->next;
		p->next = tmp;
		return start;
	} else {
		printf("4\n");
		p = new_first;
		while (p->next != tmp) p = p->next;
		p->next = NULL;
		node * start = quick_list(new_first,NULL);
		p = start;
		while ( p->next != NULL) p = p->next;
		p->next = tmp;
		
		node * end = quick_list(tmp->next,NULL);
		tmp->next = end;
		return start;
	}
	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章