0
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
struct node* next;
} ;
struct node* largest(struct node** first)
{
struct node* largest = *first;
struct node* prev = NULL;
struct node* temp_prev = NULL;
for(;first != NULL; first = first -> next)
{
if (first -> val > largest -> val)
{
largest = first;
prev = temp_prev;
}
temp_prev = first;
}
if(prev != NULL)
prev -> next = largest -> next;
largest -> next = NULL;
return largest;
}
struct node* sel_sort(struct node** list)
{
struct node* head = NULL;
struct node* temp_largest = NULL;
while (*list)
{
head = largest(list);
head->next=temp_largest;
temp_largest = head;
}
*list = head; // note sets the input pointer to the new list.
return head;
}
void print_list(struct node* first)
{
struct node* temp;
for (temp = first; temp != NULL; temp = temp->next)
{
printf("%d\n", temp->val);
}
}
void main() {
struct node* r = malloc(sizeof(struct node));
struct node* s = malloc(sizeof(struct node));
struct node* t = malloc(sizeof(struct node));
struct node* w = malloc(sizeof(struct node));
struct node* q = malloc(sizeof(struct node));
r->val = 2;
r->next = s;
s->val = 10;
s->next = t;
t->next = w;
t->val = 3;
w->val = 1;
w->next = q;
q->val = 6;
q->next = NULL;
printf("\nBefore Sort:\n");
print_list(r);
printf("\nSorted:\n");
struct node* sorted = sel_sort(&r);
print_list(sorted);
}
简而言之,以上是对单向链表的选择排序。我遇到了sel_sort方法中出现无限循环的问题,因为无论我称多少次最大的方法,都会将一个节点留在原始列表中。除此之外,我的代码似乎工作,但我怎么解决这个小问题?为什么选择排序时一个元素保留在原始列表中?
头=最大(温度); 如果你看,这会从列表中删除一个节点,并且直到只剩下一个节点。这就是为什么卡住了,但我无法弄清楚如何解决这个问题。 编辑:看最大的功能 – 2013-02-28 04:14:27
哦,我刚刚得到的那个人,我忘了引用它作为指针,让我试试看,谢谢! – 2013-02-28 04:17:20
@JonathanSwiecki更新即将到来,它是您的'最大()'从原始列表中提取节点的方式。 – WhozCraig 2013-02-28 04:17:20