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