【发布时间】:2014-08-31 01:55:45
【问题描述】:
我正在尝试使用冒泡排序按字母顺序对链接列表进行排序,但是在运行程序时出现了段错误。我可以在排序之前打印出名称,但是当我对它们进行排序并尝试显示它们时,它不起作用。
这是我拥有的代码,我想要的输出只是按顺序显示名称。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX_STR_LEN 25
typedef struct Data_ {
char *name;
struct Data_ *next;
} Data;
Data* bubble_sort(Data *list);
Data* read_from_file(const char *file, const int size);
void display(Data *list);
void push(Data **head, char *name);
int main(int argc, char **argv) {
if(argc != 2){
printf("Not enough parameters!");
exit(0);
}
Data *head = NULL;
int size = 10;
head = read_from_file(argv[1], size);
printf("\nBefore sort");
display(head);
printf("\nBubble Sort\n");
head = bubble_sort(head);
display(head);
}
Data* bubble_sort(Data *head) {
int count = 0, i;
Data *start = head;
Data *curr = NULL;
Data *trail = NULL;
Data *temp = NULL;
//grab the count
while(start != NULL) {
count++;
start = start->next;
}
for( i = 0; i < count; ++i) {
curr = trail = head; //set curr and trail at the start node
while(curr->next != NULL){
if(strcmp(curr->name, curr->next->name) > 0) {
temp = curr->next;
curr->next = curr->next->next;
temp->next = curr;
if(curr==head)
head = trail = temp;
else
trail->next = temp;
curr = temp;
}
trail = curr;
curr = curr->next;
}
}
return head;
}
void push(Data **head, char *name) {
Data *temp = malloc(sizeof(Data));
temp->name = strdup(name);
temp->next = *head;
*head = temp;
}
Data* read_from_file(const char *file, const int size) {
FILE *input;
input = fopen(file, "r");
Data *new_ = (Data*)malloc(sizeof(Data*));
new_->next = NULL;
int i;
char name[MAX_STR_LEN];
for(i = 0; i < size; i++) {
fscanf(input, "%24s", &name);
push(&new_, name);
}
return new_;
}
void display(Data *list) {
Data *current = list;
while(current->next != NULL) {
printf("\n%s", current->name);
current = current->next;
}
}
我读到的名字列表是
Derek
Drew
Randell
Terrell
Carmen
Colin
Eddy
Pablo
Lamont
Dexter
【问题讨论】:
-
用
-g编译,它会告诉你它在哪里是段错误。那将非常有用。 -
缺乏一致的缩进使得语句按照它们的意图组合在一起变得不清楚(主要看最后一个 if/else 语句)
-
curr->next = curr->next->next;这可能是你的问题。当你在列表末尾时会发生什么?对我来说,这听起来像是一个空指针 deref。 -
@Jashaszun 我不一定会称之为代码审查,因为工作代码的必要条件不满足。
-
Data *new_ = (Data*)malloc(sizeof(Data*));应该是Data *new_ = (Data*)malloc(sizeof(Data));
标签: c string linked-list bubble-sort