연결리스트 내림차순 정렬 질문입니다.
글쓴이: 강동우@Google / 작성시간: 수, 2019/12/04 - 2:52오후
#include <stdio.h>
#include <string.h>
typedef struct student_info SINFO;
void insert_node(SINFO *student);
struct student_info
{
char id[16];
char name[20];
int grade;
struct student_info *next;
};
SINFO *listhead = NULL;
void get_studentinfo();
void print_list();
void delete_list();
void main()
{
get_studentinfo();
print_list();
}
void get_studentinfo()
{
SINFO student;
printf("학생 정보를 입력하세요.\n");
printf("종료하려면 -1을 입력하세요.\n");
while (1)
{
printf("학번: ");
scanf("%s", student.id);
if (strcmp(student.id, "-1") != 0)
{
printf("이름: ");
scanf("%s", student.name);
printf("성적: ");
scanf("%d", &student.grade);
insert_node(&student);
printf("\n");
}
else
break;
}
}
void insert_node(SINFO *student)
{
SINFO *search, *previous;
SINFO *temp = (SINFO*)malloc(sizeof(SINFO));
strcpy(temp->id, student->id);
strcpy(temp->name, student->name);
temp->grade = student->grade;
temp->next = listhead;
listhead = temp;
search = listhead;
previous = NULL;
while (search != NULL)
{
if (temp->grade < search->grade)
{
previous = search;
search = search->next;
}
else
break;
if (previous == NULL)
{
temp->next = listhead;
listhead = temp;
}
else
{
temp->next = search;
previous->next=temp;
}
}
}
void delete_list()
{
SINFO *temp = listhead;
while (listhead != NULL)
{
listhead = listhead->next;
free(temp);
temp = listhead;
}
}
void print_list()
{
SINFO *search;
search = listhead;
printf("\n%16s%16s%6s\n", "학번", "이름", "성적");
printf("========================================================\n");
while (search != NULL)
{
printf("%16s", search->id);
printf("%16s", search->name);
printf("%6d\n", search->grade);
search = search->next;
}
delete_list();
}
코드를 이렇게 짰는데 출력까지 잘 됩니다. 그런데 정렬이 안되고 순서 역순으로만 출력이 됩니다. 성적 내림차순으로 정렬하고 싶은데 어디가 잘못된건지를 모르겠어요.Forums:


댓글 달기