您的位置:首页 > 职场人生

曾经遇到的一个面试题,快速排序用链表实现,算法和以前的相似,需要注意一些细节处理

2012-08-31 14:37 806 查看
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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐