【发布时间】:2014-02-18 18:24:39
【问题描述】:
我正在尝试使用 C 中的指针操作对单链表进行冒泡排序。我在网站上查看了其他一些冒泡排序的实现,但我觉得这里的代码逻辑应该是有意义的。即便如此,还是进入了无限循环。任何帮助将不胜感激!
int counter;
struct node* current = head;
struct node* previous = (struct node*) malloc(sizeof(struct node));
struct node* next = (struct node*) malloc(sizeof(struct node));
for (counter = 0; counter < num_nodes; counter++){
current = head;
next = current->m_next;
while(next != NULL){
int compare = strcmp(current->m_last_name, next->m_last_name);
if (compare > 0){
if (current == head){
head = next;
}
previous->m_next = next;
current->m_next = next->m_next;
next->m_next = current;
previous = next;
next = current->m_next;
}
else {
previous = current;
current = current->m_next;
next = current->m_next;
}
}
}
printf("Loop completely done\n");
}
【问题讨论】:
-
这不是双向链表吗?每个节点都有下一个和上一个指针...
-
calloc() 而不是 malloc() 会很好,所以我们知道指针开始为空。必须猜测你的节点声明(我猜是单链接的?)
-
嗯。缺少太多代码,甚至没有 cmets 来指示您删除了哪些代码(好吧,除非这 是 所有代码,在这种情况下,哎呀)。例如,以前是如何真正初始化的。等等。
-
找到一个进入无限循环的列表。在一张纸上写下您认为应该按顺序执行的每条语句。现在在调试器中遍历您的算法。执行不在您列表中的语句的那一刻,这就是错误所在。
-
您的
mallocs 似乎触发了内存泄漏。你写next=malloc(),四行之后,你写next=...。 malloc 后next指向的内存丢失了!冒泡排序可以不使用malloc。只需仔细修改您的指针...
标签: c list sorting linked-list bubble-sort