728x90
학번과 성적을 입력받으면
학번에 따라서 자동 정렬되는 연결 리스트 (링크드 리스트) 예제
코드
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define LEN sizeof(struct Student)
struct Student
{
int num;
float score;
struct Student *next;
};
int n = 0;
void print(struct Student * head);
struct Student * insert(struct Student * head, struct Student * stud)
{
if(head == NULL)
{
head = stud;
}
else
{
struct Student *temp;
if(head->num > stud->num)
{
temp = head;
head = stud;
stud = temp;
head->next = temp;
}
else
{
temp = head;
if(temp->next != NULL)
{
do
{
if(temp->next->num > stud->num)
{
stud->next = temp->next;
temp->next = stud;
break;
}
temp = temp->next;
}while(temp->next != NULL);
}
if(temp->next == NULL)
temp->next = stud;
}
}
return head;
}
int main()
{
struct Student *head = NULL, *stud;
int num;
float score;
while(1)
{
scanf_s("%d %f", &num, &score);
if(num == 0)
break;
stud = (struct Student*)malloc(LEN);
stud->num = num;
stud->score = score;
stud->next = NULL;
head = insert(head, stud);
}
printf("\n\n");
print(head);
system("pause");
return 0;
}
void print(struct Student * head)
{
struct Student * p;
p = head;
if(head != NULL)
{
do{
printf("%d %.1f\n", p->num, p->score);
p = p->next;
}while(p != NULL);
}
}
결과
728x90
반응형
'Application > C++' 카테고리의 다른 글
[C++] 숫자 쉼표(금액) 표시 하기 (Comma) (0) | 2023.11.08 |
---|---|
[C++] 2중 포인터 동적 할당 (0) | 2023.03.16 |
[C++] enum 중복 값 쓰기 (0) | 2022.12.22 |