연결리스트로 구현한 거 좀 봐주세요ㅠㅠ
허우룩
동적으로 연결리스트를 만들어서 오름차순으로 정렬하는 것부터 코드 작성한 담에 정렬안된 것은 출력할 때 눈에 잘 보이라고 덧붙였는데 갑자기 맨처음 들어오는 값이 짤려서 나오네요;;;;
실행은 잘 되는데 정렬전의 값을 추가로 구현하고 난 이후로 정렬 후의 값이 맨 처음 값이 1개 빼고 정렬되서 나옵니다;;;
아예 안되는 것도 아니고 이렇게 되니까 좀 당혹스럽네요ㅠㅠ 아 그리고 이렇게 구현한게 힙을 이용한 연결리스트 인가요??
add로 선언한 녀석이 지역변수로 쓰이는데 동적할당한 애를 넣어줘서 뭐 그렇게 된다고 글을 본 거 같은데, 완벽하게 정리가 안되긴 하네요
마지막으로 이걸 빅오로 본다면 o(n^2)으로 보면 될까요?? 리스트 갯수만큼 for 루프를 돌고 addnode함수에 들어가서도 while
문에서 처음부터 끝까지 돌면 n^2으로 돈다고 보면 될 것같은데 맞는지 모르겟네요;;질문 내용 :#include stdio.h
#include windows.htypedef struct node
{
struct node *link;
int data;
}node;typedef struct nodehead
{
struct node *start;
}nodehead;typedef struct subhead
{
struct node *start;
}subehead;//사용할 함수 선언
nodehead *init();
subehead *sub_init();
void addnode(nodehead *trace, subhead *sub);
void printnode(nodehead *trace, subhead *sub);int main(void)
{
nodehead *head;
subhead *sub;
int i, size; head = init(); //head 초기화
sub = sub_init(); //sub 초기화 printf(리스트의 크기를 입력하세요: );
scanf(%d, &size);
for(i=0;isize;i++)
addnode(head, sub);
printnode(head, sub);
return 0;
}//head 초기화
nodehead *init(void)
{
nodehead *head;
head = (nodehead*)malloc(sizeof(nodehead));
head-start = null;
return head;
}subhead *sub_init(void)
{
subhead *sub;
sub = (subhead*)malloc(sizeof(subhead));
sub-start = null;
return sub;
}void addnode(nodehead *trace, subhead *sub)
{
node *add; //추가되는 node
node *next_trace; //head를 추적하기 위해 사용
node *temp; //add 부분 데이터 및 링크 교제를 위한 임시 저장용 node *store; //정렬 전의 값 저장용
node *store_trace; //sub를 추적하기 위해 사용 int data_buf; //입력받을 값 저장 add = (node *)malloc(sizeof(node));
store = (node *)malloc(sizeof(node)); printf(\n정수를 입력하세요: );
scanf(%d, &data_buf);
add-data = data_buf;
add-link = null; store-data = data_buf;
store-link = null;
//sub의 조건 부분(입력되는 순서대로 추가함)
if(sub-start == null) //처음 시작 부분
{
sub-start = store; //추가
return;
}
else
{
store_trace = sub-start; while(store_trace-link != null)
store_trace = store_trace-link;
store_trace-link = store;
} //head의 조건 부분(정렬하면서 추가함)
if(trace-start == null)
{
trace-start = add; //추가
return;
}
else
{
next_trace = trace-start; if(next_trace-data data_buf)
{
add-link = trace-start; //head주소가 가르키는 주소 넘겨줌.
trace-start = add; //add가 가진 값들을 넘겨줌.
}
else
{
//링크의 끝까지 반복문을 수행함.
while(next_trace-link != null)
{
//next_trace-link-data는 head가 가르키고 있던 부분의 data값임.
if(next_trace-link-data data_buf)
{
temp = next_trace-link;
add-link = temp;
break;
}
next_trace = next_trace-link; //이전 head포인터가 저장됨.
}
next_trace-link = add; //최종적으로 head포인터가 변경됨.
}
}
}void printnode(nodehead *trace, subhead *sub)
{
node *add;
node *store; store = sub-start;
add = trace-start; printf(\n=============================\n);
printf(정렬 전의 값은: );
while(store != null)
{
printf(%d , store-data);/fota);
store = store-link;
}
printf(\n=============================\n); printf(정렬 후의 값은: );
while(add != null)
{
printf(%d , add-data);
add = add-link;
}
printf(\n=============================\n);
}